我正在使用JavaScript(Ionic 2 / Angular)开发一个简单的购物车解决方案。
在PHP中,我只是执行以下操作:
<?php
$cart = array(
48131 => array(
'size' => 'STANDART',
'qty' => 1,
)
);
print_r($cart);
48131
是index
,因此我可以轻松删除它(因为我知道key
是48131
)。
这是我的JavaScript代码(示例):
function addToCart() {
this.cart = [];
this.cart.push({
id: this.id,
size: this.size,
qty: this.qty
});
console.log(this.cart);
}
这就是我得到的 -
看起来push方法只是添加另一个键,从0开始(我猜这是正常的)。我尝试了很多东西,我做不到......有人可以帮忙吗?
答案 0 :(得分:0)
this.cart = {};
function addToCart() {
this.cart[this.id]= {
size: this.size,
qty: this.qty
};
console.log(this.cart);
}
答案 1 :(得分:0)
简单地做
function addToCart() {
this.cart = [];
this.cart['48131'] = {
id: this.id,
size: this.size,
qty: this.qty
};
console.log(this.cart);
}
答案 2 :(得分:0)
角侧的推车应该有一个物体。并将一个项目放入其中: var cart = {}; cart [id] = {prop1:val1,prop2:val2};