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;
}

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

其他回答

有一个等效函数:

includes()

看这里: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

带下划线的in_array的等效形式是_.indexOf

例子:

_.indexOf([3,5,8], 8);//返回索引为8的2 _.indexOf([3,5,8], 10);//返回-1,未找到

PHP:

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

我在JS中的解决方案:

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

jQuery解决方案是可用的,检查文档在这里: http://api.jquery.com/jquery.inarray/

$.inArray( 10, [ 8, 9, 10, 11 ] );

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