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

类似于PHP的in_array函数?


当前回答

如果你打算在一个类中使用它,如果你希望它是功能性的(并且在所有浏览器中工作):

inArray: function(needle, haystack)
{
    var result = false;

    for (var i in haystack) {
        if (haystack[i] === needle) {
            result = true;
            break;
        }
    }

    return result;
}

希望它能帮助到一些人:-)

其他回答

如果你需要所有的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;
  };
}

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

haystack.find(value => value == needle)

其中haystack是一个数组,needle是数组中的一个元素。如果元素未找到,则返回未定义,否则返回相同的元素。

现在有了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)

PHP:

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

我在JS中的解决方案:

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