2

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();
                }

            }
        });
Oscar Godson
  • 31,662
  • 41
  • 121
  • 201
  • Search for `Array.prototype.indexOf`. eg http://stackoverflow.com/questions/1744310/how-to-fix-array-indexof-in-javascript-for-ie-browsers – Sean Hogan Nov 01 '10 at 09:27

3 Answers3

5

There 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.

Sarfraz
  • 377,238
  • 77
  • 533
  • 578
4

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 becomes:

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

gblazex
  • 49,155
  • 12
  • 98
  • 91
1

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.

jcomeau_ictx
  • 37,688
  • 6
  • 92
  • 107