为什么以下“in”运算符没有在此数组中找到字符串?

时间:2016-03-22 10:16:25

标签: javascript

我正在尝试编写一个函数来检查密钥是否属于“count”类别:

isCountKey (key) {
  const countKeys = [
    'buildingCount',
    'panoramaCount'
  ] // TODO find a better way to check for count keys
  console.log(key)
  console.log(key in countKeys)
  return key in countKeys
}

console.log但是,即使密钥为falsebuildingCount,也始终会返回panoramaCount

name
List.vue?2658:38 false
List.vue?2658:42 number
List.vue?2658:38 false
List.vue?2658:42 buildingCount
List.vue?2658:38 false
List.vue?2658:42 panoramaCount
List.vue?2658:38 false

为什么会这样?

2 个答案:

答案 0 :(得分:0)

in测试是否存在与字符串具有相同名称的属性,而不是具有相同的属性。使用"length""0"进行测试即可。

使用the indexOf method在数组中搜索匹配值。

答案 1 :(得分:0)

使用indexOf代替

// If element is not in array, indexOf returns -1, not returning -1 means the key is in the array

var isKeyInArray = (countKeys.indexOf(key) != -1); 
console.log(isKeyInArray)