I have 1 or more items in an array, for this example let's say they are [65, 66, 67]
how can (if it's even possible) do only a single if conditional to check for a match.
For example:
var keyArray = [65, 66, 67];
if(e.keyCode == any item in keyArray){
//Then do this
}
Try to make a jQuery plugin that a user can map multiple keys to a single action. E.g. pressing a, b, or c could alert "You're pressing either a, b, or c";
Here is my real sample code that isn't working:
$this.keydown(function(e){
if(e.keyCode in keySplit){
if(typeof callback == 'function'){
callback();
e.preventDefault();
}
}
});
I have 1 or more items in an array, for this example let's say they are [65, 66, 67]
how can (if it's even possible) do only a single if conditional to check for a match.
For example:
var keyArray = [65, 66, 67];
if(e.keyCode == any item in keyArray){
//Then do this
}
Try to make a jQuery plugin that a user can map multiple keys to a single action. E.g. pressing a, b, or c could alert "You're pressing either a, b, or c";
Here is my real sample code that isn't working:
$this.keydown(function(e){
if(e.keyCode in keySplit){
if(typeof callback == 'function'){
callback();
e.preventDefault();
}
}
});
Share
Improve this question
edited Nov 1, 2010 at 9:22
Oscar Godson
asked Nov 1, 2010 at 9:15
Oscar GodsonOscar Godson
32.8k42 gold badges125 silver badges206 bronze badges
1
-
Search for
Array.prototype.indexOf
. eg stackoverflow./questions/1744310/… – Sean Hogan Commented Nov 1, 2010 at 9:27
3 Answers
Reset to default 5There is $.inArray
method in jQuery for that.
Description: Search for a specified value within an array and return its index (or -1 if not found).
Or see in_array
javascript function in phpjs.
In modern browsers you have Array.indexOf
method. For older browsers it's very easy to create a similar method:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement) {
var len = this.length;
for (var i = 0; i < len; i++) {
if (this[i] === searchElement)
return i;
}
return -1;
};
}
Now you conditionally defined Array.indexOf
, so it will be available in every platform. Your code bees:
var keyArray = [65, 66, 67];
if ( keyArray.indexOf( e.keyCode ) > -1 ) {
//Then do this
}
note, if you want to fully replicate the Array.indexOf
, see: MDC indexOf
The "in" operator only sees the keys, not the values, and the keys of [65,66,67] are, of course, [0,1,2]. So you'd check using:
var keyArray = {65:65, 66:66, 67:67};
if (e.keyCode in keyArray) {
// whatever
}
The keyArray could as well be {65:"", 66:"", 67:""}; again, it's the key of the key-value pair that counts.