简体   繁体   English

如果使用JavaScript,如何检查数组中的多个元素?

[英]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. 我在一个数组中有一个或多个项目,对于这个例子,假设它们是[65, 66, 67]如何(如果它甚至可能)只做一个if条件检查匹配。

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. 尝试制作一个jQuery插件,用户可以将多个键映射到单个操作。 Eg pressing a, b, or c could alert "You're pressing either a, b, or c"; 例如,按a,b或c可以提示“你正在按a,b或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. jQuery中有$.inArray方法。

Description: Search for a specified value within an array and return its index (or -1 if not found). 描述:在数组中搜索指定的值并返回其索引(如果未找到,则返回-1)。

Or see in_array javascript function in phpjs. 或者在phpjs中查看in_array javascript函数。

In modern browsers you have Array.indexOf method. 在现代浏览器中,您有Array.indexOf方法。 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. 现在您有条件地定义了Array.indexOf ,因此它将在每个平台上都可用。 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 注意,如果你想完全复制Array.indexOf ,请参见: 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]. “in”运算符只能看到键,而不是值,而[65,66,67]的键当然是[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:""}; keyArray也可以是{65:“”,66:“”,67:“”}; again, it's the key of the key-value pair that counts. 再次,这是关键值对的关键。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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