2014-12-02 31 views
0

我想使用indexOf來確定是否傳遞它的obj已經在數組中。它似乎沒有工作。以下是將項目添加到數組的代碼。Shopping Basket indexOf

的Javascript:

add: function(id, item, description, price, itemObj) { 
      if(items.indexOf(itemObj) == 1) { 
       console.log(itemObj); 
       items.forEach(function(item){ 
        if(item.id === id){ 
         item.itemCount += 1; 
        }; 
       }); 
      } else { 
       console.log(itemObj); 
       items.push(new basket.Item(id, item, description, price)); 
      }; 
      basket.print(); 
     } 

更描述性的,它永遠不會運行if語句,將始終採取傳遞一個新的對象數組。

+0

您有調用函數中的項目,並以與調用不一致的方式使用下面的項目。 – rfornal 2014-12-02 18:09:48

+0

很抱歉,你能解釋一下嗎? – hudsond7 2014-12-02 18:10:28

+0

您在函數中使用'item' ** s **的函數(id,'item',description ...進一步,而不是indexOf的項目,而foreach函數中的'item'的forEach。 – rfornal 2014-12-02 18:12:08

回答

0

我不確定indexOf是否查找匹配數組中的值。我認爲它只是匹配一個字符串中的子字符串。另外,你應該檢查返回值大於或等於零:

if(items.join("").indexOf(itemObj) >= 0) { 

好了,加入函數連接的價值觀來建立一個字符串,例如:

items = ["first", "second", "third"]; 

items.join(""); 

// now items = "firstsecondthird"; 

var ind = items.join("").indexOf("first"); //ind here is greater or equal than 0 

var ind = items.join("").indexOf("firstone"); //ind here is equal -1 (any comparison in the string) 

注意的indexOf正在搜索用於字符串中的第一個比較。如果您有此字符串abcdefga,並且您在尋找aindexOf,則返回的值將爲0,因爲第一次比較是在開始處。搜索最後的比較將是lastIndexOf

+0

你能解釋一下好嗎? – hudsond7 2014-12-02 18:18:28

+0

@ hudsond7當然。 – Verhaeren 2014-12-02 18:30:43

+0

這個答案是錯誤的 - ''Array.prototype.indexOf()'確實存在(雖然它在一些老版本的瀏覽器中是不可用的),所提出的解決方案只適用於字符串匹配,因爲items.join(「」)將數組的每個元素轉換爲一個字符串。在對象的情況下,它可能是'[object Object]',所以它不會太有用。 – rhino 2014-12-02 18:47:29