[英]How can I group the values in the object and push them in an array in JS?
[英]How do I push a group of values to an array with Javascript push()?
有人可以在這里發現錯誤嗎? 檢查點1觸發,但不是檢查點2。無法弄清楚我的陳述出了什么問題。
<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>
items = {
itemID: "B17",
itemPrice: 17,
itemQty: 1
};
不是數組。 它應該是:
items =[{
itemID: "B17",
itemPrice: 17,
itemQty: 1
}];
問題在於項目不是數組,而是對象。 小提琴: 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.