好的,我有这个阵列:
var data = [1, 2, {a: 1}, [43], '3'];
我需要检查并查看以下元素是否在此数组中:
1 -> should return true
43 -> should return false
3 -> should return false
'3' -> should return true
这就是我所拥有的:
function has(list, element) {
console.log(list); //gives me data = [1, 2, {a: 1}, [43], '3'];
console.log(element); //gives me first 1, then 43, then 3, then '3'
for (var i = 0; i < list.length; i++) {
var decision = true;
switch (decision) {
case (list[i] == element):
console.log("Yes in array.");
decision = true;
break;
case (element !== list[i]):
console.log("Not in array.");
decision = false;
break;
}
}
return decision;
}
这是我在控制台中获得的内容:https://imgur.com/a/crcJp
主要问题是如何检查类型(元素和数组)是否匹配?我尝试使用===但它没有用。
答案 0 :(得分:2)
您只需使用includes
中的Array.prototype
功能。
var data = [1, 2, {a: 1}, [43], '3'];
console.log(data.includes(1)); // true
console.log(data.includes(43)); // false
console.log(data.includes(3)); // false
console.log(data.includes('3')); // true
&#13;
答案 1 :(得分:0)
使用indexOf()
:
var data = [1, 2, {a: 1}, [43], '3'];
function has(list, element) {
return list.indexOf(element) > -1 ? true : false;
}
console.log(has(data,3)); //false
console.log(has(data,'3')); //true