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

类似于PHP的in_array函数?


当前回答

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

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

其他回答

PHP:

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

我在JS中的解决方案:

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

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

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

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

如果索引不是按顺序排列的,或者索引不是连续的,那么这里列出的其他解决方案中的代码将会中断。一个更好的解决方案可能是:

function in_array(needle, haystack) {
    for(var i in haystack) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

而且,作为额外的奖励,这里有与PHP的array_search(用于查找数组中元素的键值)等效的函数:

function array_search(needle, haystack) {
    for(var i in haystack) {
        if(haystack[i] == needle) return i;
    }
    return false;
}