2016-03-22 15 views
0

我想寫來檢查,如果該鍵屬於「計數」類別的函數:爲什麼下面的「in」運算符沒有在這個數組中找到字符串?

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然而,總是返回false,即使關鍵是buildingCountpanoramaCount

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 

這是爲什麼?

+1

您有一個數組,其作爲數字索引...使用對象..'countKeys = {[ 'buildingCount':真實, 'panoramaCount':真 }' –

+0

,因爲這裏的鍵是0和1 – Alexander

+0

或使用'countKeys .indexOf(key)!= -1' –

回答

0

in測試,看看是否具有相同名稱的屬性爲字符串存在,而不是一個具有相同財產。使用"length""0"進行測試,它會起作用。

使用the indexOf method在數組中搜索匹配值。

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) 
相關問題