2015-04-30 38 views
0

這是行不通的嗎?我認爲這是有效的,但它不起作用。使用「in」檢查字符串是否在數組中

var items = ["image", "text"]; 
console.log(this.type) 
if(this.type in items){ 
    console.log("here") 
} 

console.log(this.type)顯示image,但here永遠不會顯示。

我做錯了什麼,或者我在想錯誤的語言?

+0

您必須指定索引號不是值。 – chRyNaN

回答

8

in檢查對象的屬性名稱。

在這裏,你需要的是indexOf

if (~items.indexOf(this.type)){ 

注:這是使用bitwise not operator

if (items.indexOf(this.type)!==-1){ 

一個短版。

+0

@GlenSwift我編輯來解釋那點 –

+0

啊涼快!我想知道'〜'是什麼意思! –

+0

我明白了,謝謝 –

0

你可以做

var items = ["image", "text"]; 
 
var item = "image"; 
 
if (items.indexOf(item) > -1) { 
 
    console.log("here"); 
 
}

Array.indexOf() MDN

0

的 「中的」 在JavaScript中的關鍵字僅適用於鍵和對象的屬性。我會做的方式:

if (items.indexOf(this.type) !== -1) 

這將返回類型的索引你正在尋找或-1,如果它不存在。如果它不等於-1,那麼它就在那裏。

相關問題