JavaScript中是否有一种方法可以比较一个数组中的值,并查看它是否在另一个数组中?
类似于PHP的in_array函数?
JavaScript中是否有一种方法可以比较一个数组中的值,并查看它是否在另一个数组中?
类似于PHP的in_array函数?
当前回答
现在有了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;
}
希望它能帮助到一些人:-)
function in_array(needle, haystack){
return haystack.indexOf(needle) !== -1;
}
你可以简单地使用“includes”函数,就像w3schools这节课中解释的那样
它看起来像
let myArray = ['Kevin', 'Bob', 'Stuart']; 如果(myArray.includes(凯文)) console.log('Kevin is here');
jQuery解决方案是可用的,检查文档在这里: http://api.jquery.com/jquery.inarray/
$.inArray( 10, [ 8, 9, 10, 11 ] );
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;
}