2012-11-22 42 views
13

我有一個變量:找出變量是否在數組中?

var code = "de"; 

而且我有一個數組:

var countryList = ["de","fr","it","es"]; 

有人能幫助我,我需要檢查,看看是否變量是countryList陣列內 - 我的嘗試是在這裏:

if (code instanceof countryList) { 
     alert('value is Array!'); 
    } 

    else { 
     alert('Not an array'); 
    } 

,但我得到的console.log以下錯誤,當它的運行:

TypeError: invalid 'instanceof' operand countryList

+1

-1標籤問題如果在接受答案之前給出的相同答案未被接受... –

回答

12

jQuery有一效用函數找到一個元素是否在陣列存在或不

$.inArray(value, array) 

它如果值不存在於陣列返回值的指數中array-1。因此您的代碼可以是這樣的

if($.inArray(code, countryList) != -1){ 
    alert('value is Array!'); 
} else { 
    alert('Not an array'); 
} 
18

您需要使用Array.indexOf

if (countryList.indexOf(code) >= 0) { 
    // do stuff here 
} 

請不在於它是不是在和IE8(可能還有其他舊版瀏覽器)之前支持。瞭解更多關於它here

+2

請注意,Array8中不支持'Array.indexOf'(可能還有其他傳統瀏覽器)。在https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf#Browser_compatibility – David

+1

上使用shim對於舊版瀏覽器,實現Array.indexOf非常簡單,如果這是必需的。 – tjameson

2

jQuery中,您可以利用

jQuery.inArray() -Search的用於陣列中的指定值,並返回它的索引(或-1,如果未找到)。

if ($.inArray('de', countryList) !== -1) 
{ 
} 

對JavaScript的解決方案檢查現有How do I check if an array includes an object in JavaScript?

Array.prototype.contains = function(k) { 
    for(p in this) 
     if(this[p] === k) 
      return true; 
    return false; 
} 
for example: 

var list = ["one","two"]; 

list.contains("one") // returns true 
+1

簡單問題y有-1?請對此評論 –

+1

我認爲誰低估了(不是我),這是因爲它最初只用JavaScript標記,並且無法假定他正在使用庫。但是現在很明顯他想要JQuery,所以+1作爲正確的答案。 – lifetimes

+0

@ user1394965 - 問題是-1在OP –

0

使用jQuery的

您可以使用$.inArray()

$.inArray(value, array) 

返回目錄的項目或-1,如果沒有找到

+1

選擇答案後發生這是我假設的jQuery,而不是核心Javascript。 – tjameson

+0

是的,這是jQuery,使用jQuery的問題是什麼! –

+0

好的,謝謝你:) –

2

instanceof是用於檢查對象是否是特定類型(這是一個完全不同的主題)的。所以,而不是你寫的代碼,你應該在數組中查找。您可以檢查這樣的每一個元素:

var found = false; 
for(var i = 0; i < countryList.length; i++) { 
    if (countryList[i] === code) { 
    found = true; 
    break; 
    } 
} 

if (found) { 
    //the country code is not in the array 
    ... 
} else { 
    //the country code exists in the array 
    ... 
} 

或者你可以使用使用indexOf()功能的簡單的方法。每個數組都有一個indexOf()函數,它循環一個元素並返回數組中的索引。如果找不到該元素,則返回-1。所以,你檢查輸出的indexOf(),看它是否已經找到任何您的字符串匹配的數組中:

if (countryList.indexOf(code) === -1) { 
    //the country code is not in the array 
    ... 
} else { 
    //the country code exists in the array 
    ... 
} 

我會使用第二算法,因爲它更簡單。但是第一個算法也很好,因爲它更具可讀性。兩者都有相同的收入,但第二個有更好的表現,並且更短。但是,舊版瀏覽器不支持它(IE < 9)。

如果您使用的是JQuery庫,則可以使用可在所有瀏覽器中工作的​​函數。它與indexOf()相同,如果找不到要查找的元素,則回退-1。所以你可以這樣使用它:

if ($.inArray(code, countryList) === -1) { 
    //the country code is not in the array 
    ... 
} else { 
    //the country code exists in the array 
    ... 
} 
1

對於純粹的JavaScript解決方案,你可以遍歷數組。

function contains(r, val) { 
    var i = 0, len = r.length; 

    for(; i < len; i++) { 
     if(r[i] === val) { 
      return i; 
     } 
    } 
    return -1; 
} 
使用jQuery,如果你想獲得的jQuery的解決方案...其missleading,第二次同樣的答案被賦予在這之前沒有被標記爲asnwer這個答案Y ...我不知道怎麼回事,這樣
相關問題