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

类似于PHP的in_array函数?


当前回答

var value = 'a';
var array = ['a', 'b', 'c'];
if(array.indexOf(value)){
    // exists in array
} else {
   // Not exists in array
}

其他回答

function in_array(what, where) {
    var a=false;
    for (var i=0; i<where.length; i++) {
        if(what == where[i]) {
            a=true;
            break;
        }
    }
    return a;
}

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

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

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

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