JavaScript中是否有一种方法可以比较一个数组中的值,并查看它是否在另一个数组中?

类似于PHP的in_array函数?


当前回答

如果你需要所有的PHP可用参数,使用这个:

function in_array(needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    }
    else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
    return false;
}

其他回答

数组中。indexOf是在JavaScript 1.6中引入的,但旧的浏览器不支持它。值得庆幸的是,Mozilla的伙计们已经为你做了所有艰苦的工作,并为你提供了以下兼容性:

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

甚至还有一些方便的使用代码片段供您编写脚本。

有一个叫Locutus的项目,它在Javascript和in_array()中实现了PHP函数,你可以像在PHP中使用一样使用它。

用法示例:

in_array('van', myArray);

in_array(1, otherArray, true); // Forcing strict type
var value = 'a';
var array = ['a', 'b', 'c'];
if(array.indexOf(value)){
    // exists in array
} else {
   // Not exists in array
}

PHP:

if (in_array('a', ['a', 'b', 'c'])) {
   // do something if true
}

我在JS中的解决方案:

if (['a', 'b', 'c'].includes('a')) {
   // do something if true
}
var a = [1,2,3,4,5,6,7,8,9];

var isSixInArray = a.filter(function(item){return item==6}).length ? true : false;

var isSixInArray = a.indexOf(6)>=0;