2015-08-13 65 views
0

我正在嘗試在數組中找到一個項目。我的變量a只有-1,所以在我的數組中找不到該項目,但該項目肯定是數組。JavaScript Array indexOf()方法不起作用

var sortiment = []; 
var geschmack = []; 
var kategorie = []; 

function filterOptions(eigenschaft, filter){ 
    inhalt = filter + " = " + eigenschaft; 
    console.log(inhalt); 
    console.log(sortiment[0]); 
    a = sortiment.indexOf(inhalt); 
    console.log(a); 

    switch(filter) { 
     case "sortiment": 
      sortiment.push([inhalt]); 
      break; 
     case "geschmack": 
      geschmack.push([inhalt]); 
      break; 
     case "kategorie": 
      kategorie.push([inhalt]); 
      break; 
     default: 
      console.log("FAIL"); 
    } 
} 

如果找到該項目,我不想將它添加到數組中。

+0

當'indexOf()'返回-1時,您搜索的值不存在。 'console.log(sortiment)的輸出是什麼;的console.log(inhalt);'? – dsh

+3

您正在將包含單個元素(字符串)的(內部)數組推入(外部)數組,但是您正在從外部數組中搜索字符串的索引。這是行不通的。換句話說,問題很可能是geschmack.push([inhalt])。爲什麼那些方括號? – SoaperGEM

+1

@SoaperGEM您的評論應該是一個答案。 – Siguza

回答

1

你推一個包含單個元素(字符串)到(外部)數組中的(內部)數組,但是您正在從外部數組中搜索字符串的索引。這是行不通的。換句話說,問題很可能是這樣的:

geschmack.push([inhalt]); 

爲什麼那些方括號在那裏?你可能希望這樣的:

geschmack.push(inhalt); 

如果你希望顯示這一點,你的陣列將最終看起來是這樣的:

[ ["filter1=eigenschaft1"], ["filter2=eigenschaft2"] ] 

但是你不尋找["filter1=eigenschaft1"];你正在尋找"filter1=eigenschaft1",所以當然不會找到它。另外,您可以改變這一行:

a = sortiment.indexOf([inhalt]); 

但是,這整個事情似乎已經有點令人費解的,是誠實的。

+0

同意。所有這些麻煩,以避免兩次添加相同的過濾器? – SparK

+0

謝謝。沒有認出它 - 「 - 」 – Alex

0

你得到-1,因爲當你寫var sortiment = [];這意味着它不是在數組中,當你跑.IndexOf(東西)

這裏有一個refrence:http://www.w3schools.com/jsref/jsref_indexof_array.asp

function filterOptions(eigenschaft, filter){ 
    inhalt = filter + " = " + eigenschaft; 
    console.log(inhalt); 
    console.log(sortiment[0]); 
    switch(filter) { 
     case "sortiment": 
      sortiment.push(inhalt);//remove [ ] 
      break; 
     case "geschmack": 
      geschmack.push(inhalt); 
      break; 
     case "kategorie": 
      kategorie.push(inhalt); 
      break; 
     default: 
      console.log("FAIL"); 
    } 
    a = sortiment.indexOf(inhalt); //look for index after .push 
    console.log(a); 
} 
+0

看起來你稍後錯過了'sortiment.push'。 – Siguza

+0

但是你仍然從-1中得到-1,因爲你首先查找索引,如果你先執行'.push'然後執行'.IndexOf()',那麼a就是0,因爲它是數組中的第一個元素。 – Gage

+0

我正在研究'filterOptions'被多次調用的假設,但你是對的,我們沒有證據證明這實際上是這樣的... – Siguza