2011-06-15 21 views
23

可能重複:
Test for value in Javascript Array
Best way to find an item in a JavaScript Array ?
Javascript - array.contains(obj)的Javascript如果X

我通常程序在python,但最近已經開始學習JavaScript。

在Python中,這是一個完全有效的if語句:

list = [1,2,3,4] 
x = 3 
if x in list: 
    print "It's in the list!" 
else: 
    print "It's not in the list!" 

但我有poblems做在Javascript同樣的事情。

如何檢查x是否在JavaScript中的列表y?

+2

http://stackoverflow.com/questions/237104/javascript-array -containsobj – 2011-06-15 10:12:58

回答

30

使用在JS 1.6中引入的indexOf。您需要使用該頁面上的「兼容性」下列出的代碼來添加對不執行該版本JS的瀏覽器的支持。

JavaScript確實有一個in運算符,但它測試而不是值。

12

在javascript中您可以使用

if(list.indexOf(x) >= 0) 

P.S:只有在現代瀏覽器的支持。

+0

只適用於現代瀏覽器。 – 2011-06-15 10:17:11

+0

@ T.J - 採取了點。哪些瀏覽器不支持這個? – 2011-06-15 10:19:13

+0

我不知道完整的列表,但它從IE8及其下面(是的,真的)缺少。微軟最終將其添加到IE9。我認爲其他專業已有多年,不知道一些移動瀏覽器(黑莓等)。您可以查看[這裏](http://jsbin.com/uzama4/3)。 – 2011-06-15 10:54:29

4
更genric方式

,你可以像這 -

//create a custopm function which will check value is in list or not 
Array.prototype.inArray = function (value) 

// Returns true if the passed value is found in the 
// array. Returns false if it is not. 
{ 
    var i; 
    for (i=0; i < this.length; i++) { 
     // Matches identical (===), not just similar (==). 
     if (this[i] === value) { 
      return true; 
     } 
    } 
    return false; 
}; 

然後調用這個這個功能way-

if (myList.inArray('search term')) { 
    document.write("It's in the list!") 
} 
相關問題