Javascript检查数组中的元素是否为相同类型并返回true / false

时间:2018-01-23 11:13:38

标签: javascript arrays

好的,我有这个阵列:

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

主要问题是如何检查类型(元素和数组)是否匹配?我尝试使用===但它没有用。

2 个答案:

答案 0 :(得分:2)

您只需使用includes中的Array.prototype功能。

&#13;
&#13;
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;
&#13;
&#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