2013-10-26 81 views
-1

任何人都可以在這裏發現錯誤嗎?檢查點1觸發但不是檢查點2.無法弄清楚我的說法有什麼問題。如何使用Javascript push()將一組值推送到數組?

<script> 
     function shoppingCart() { 

      var item, 
       price, 
       qty, 
       items = { 
        itemID: "B17", 
        itemPrice: 17, 
        itemQty: 1 
        }; 

     function addItem(item, price, qty) { 
      alert("checkpoint 1"); 
       items.push({ 
       itemID: item,     
       itemPrice: price, 
       itemQty: qty 
       }); 
      alert("checkpoint 2"); 

     }; 

}; 
     cart = new shoppingCart(); 

     cart.addItem("b4",14,1); 
     alert(cart.items.itemID); 
    </script> 
+0

**這個問題似乎是題外話,因爲該項目是不是一個數組,OP沒有表現出自己研究的標誌** – iConnor

+0

就下來了投票還有相當快,PAL,爲一個沒有建設性的人提供。我花了數小時試圖弄清楚我做錯了什麼。從我在網上發現的數據來看,一個數組是JS中的一個對象,對於像我這樣的新手來說,這個區別有點模糊。 – user1780242

+0

一切都是JavaScript中的對象,你不會在字符串上使用'push()'嗎?這個網站不是一個調試工具。您的瀏覽器控制檯是。 – iConnor

回答

3
items = { 
    itemID: "B17", 
    itemPrice: 17, 
    itemQty: 1 
}; 

不是數組。它應該是:

items =[{ 
    itemID: "B17", 
    itemPrice: 17, 
    itemQty: 1 
}]; 
2

問題是項目不是一個數組,而是一個對象。小提琴:http://jsfiddle.net/pCc9w/

所有代碼,固定:

 function shoppingCart() { 

      var item, 
       price, 
       qty; 
       this.items = [{ 
        itemID: "B17", 
        itemPrice: 17, 
        itemQty: 1 
        }]; 



}; 

     shoppingCart.prototype.addItem = function(item, price, qty) { 
      alert("checkpoint 1"); 
       this.items.push({ 
       itemID: item,     
       itemPrice: price, 
       itemQty: qty 
       }); 
      alert("checkpoint 2"); 

     }; 
     cart = new shoppingCart(); 

     cart.addItem("b4",14,1); 
     alert(cart.items[1].itemID); 
+0

也許使原型中的addItem? –

+0

@ZekeAlexandreNierenberg你是對的,編輯和添加原型。 – pax162

相關問題