
[英]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.