2015-08-29 42 views
-2

我是超級新來javascript和學習。javascript:測試如果this.name ==數組元素

我有這段代碼,它正在運行並完成工作。

(this.name == ('nodepy') || this.name == ("nonlinear-waves-course") || this.name == ("SSP_Tools")) 

,但現在我想定義字符串數組或列表

var listOfRepos = ["nodepy", "nonlinear-waves-course", "SSP_Tools"]; 

如何去檢查是否「this.name」是「listOfRepos」?

在Python中,我可以只寫是這樣的:

this.name in listOfRepos 

同樣,我是新來的JavaScript。很少有經驗。提前謝謝你。

+0

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf –

回答

2

使用indexOf()

if (~listOfRepos.indexOf(this.name)){ 
    alert('true'); 
} 

說明:

indexOf()返回值的數組中的索引,如果它是數組中,如果不是則返回-1。我正在使用bitwise not運算符~

按位不會反轉其操作數的位。

以上也可以寫成

if (listOfRepos.indexOf(this.name) > -1) {} 
+0

不客氣! – baao

+0

推廣使用令人困惑的'〜'運算符是個壞主意。 –

+0

@torazaburo看看[這裏](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_NOT),也許這會讓你更清楚 – baao