JavaScript中是否有一种方法可以比较一个数组中的值,并查看它是否在另一个数组中?
类似于PHP的in_array函数?
JavaScript中是否有一种方法可以比较一个数组中的值,并查看它是否在另一个数组中?
类似于PHP的in_array函数?
当前回答
PHP:
if (in_array('a', ['a', 'b', 'c'])) {
// do something if true
}
我在JS中的解决方案:
if (['a', 'b', 'c'].includes('a')) {
// do something if true
}
其他回答
现在有了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)
你可以简单地使用“includes”函数,就像w3schools这节课中解释的那样
它看起来像
let myArray = ['Kevin', 'Bob', 'Stuart']; 如果(myArray.includes(凯文)) console.log('Kevin is here');
var value = 'a';
var array = ['a', 'b', 'c'];
if(array.indexOf(value)){
// exists in array
} else {
// Not exists in array
}
如果你需要所有的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;
}
haystack.find(value => value == needle)
其中haystack是一个数组,needle是数组中的一个元素。如果元素未找到,则返回未定义,否则返回相同的元素。