JavaScript中是否有一种方法可以比较一个数组中的值,并查看它是否在另一个数组中?
类似于PHP的in_array函数?
JavaScript中是否有一种方法可以比较一个数组中的值,并查看它是否在另一个数组中?
类似于PHP的in_array函数?
当前回答
haystack.find(value => value == needle)
其中haystack是一个数组,needle是数组中的一个元素。如果元素未找到,则返回未定义,否则返回相同的元素。
其他回答
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
}
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;
}
如果索引不是按顺序排列的,或者索引不是连续的,那么这里列出的其他解决方案中的代码将会中断。一个更好的解决方案可能是:
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;
}
你可以简单地使用“includes”函数,就像w3schools这节课中解释的那样
它看起来像
let myArray = ['Kevin', 'Bob', 'Stuart']; 如果(myArray.includes(凯文)) console.log('Kevin is here');