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

类似于PHP的in_array函数?


当前回答

function in_array(needle, haystack){

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

其他回答

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

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

例子:

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

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

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

对于Dojo Toolkit,您将使用Dojo . indexof()。看到dojo。用于文档的是indexOf,用于示例的是Bryan Forbes的Arrays Made Easy。

PHP:

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

我在JS中的解决方案:

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