简体   繁体   中英

How to check multiple elements in array with one if with JavaScript?

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

            }
        });

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM