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

类似于PHP的in_array函数?


当前回答

你可以简单地使用“includes”函数,就像w3schools这节课中解释的那样

它看起来像

let myArray = ['Kevin', 'Bob', 'Stuart']; 如果(myArray.includes(凯文)) console.log('Kevin is here');

其他回答

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

用法示例:

in_array('van', myArray);

in_array(1, otherArray, true); // Forcing strict type
function in_array(needle, haystack){

    return haystack.indexOf(needle) !== -1;
}

你可以简单地使用“includes”函数,就像w3schools这节课中解释的那样

它看起来像

let myArray = ['Kevin', 'Bob', 'Stuart']; 如果(myArray.includes(凯文)) console.log('Kevin is here');

现在有了Array.prototype.includes:

includes()方法确定数组是否包含某个对象 元素,返回true或false。

var a = [1, 2, 3];
a.includes(2); // true 
a.includes(4); // false

语法

arr.includes(searchElement)
arr.includes(searchElement, fromIndex)

数组中。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;
  };
}

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