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

类似于PHP的in_array函数?


当前回答

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

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

其他回答

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

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

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

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

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

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

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

    return result;
}

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

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