![](/img/trans.png)
[英]How do I count the number of items in an array that start with the highest number?
[英]How do I count the total number of items in an array based on id and quantity?
我有一个像这样的cart[]
数组:
[
{item_id: "0001", qty: "1"},
{item_id: "0002", qty: "2"},
{item_id: "0005", qty: "3"},
{item_id: "0001", qty: "5"}
]
例如,我正在尝试计算item_id == 0001
所有qty
。 问题是, item_id
可能在数组中多次出现; 在这种情况下两次。 所以我试图将所有qty
添加到一个值中。
这是我到目前为止所拥有的:
var this_item_qty = 0;
$.each(cart, function(index, value) {
if (value.item_id == "0001"){
this_item_qty = this_item_qty + value.qty;
}
console.log(this_item_qty);
// Returns 01 or 015...
});
但这似乎不起作用。 它给了我像01
和015
这样的值。 它似乎是将这些值一个一个地放在一起,而不是将它们放在一起计算。 我究竟做错了什么?
使用Number(value.qty)
var this_item_qty = 0;
$.each(cart, function(index, value) {
if (value.item_id == "0001"){
this_item_qty = this_item_qty + Number(value.qty);
}
console.log(this_item_qty);
});
你需要使用this_item_qty+= parseInt(value.qty)
它将value.qty
作为字符串并将其连接起来。 你需要:
this_item_qty = this_item_qty + parseInt(value.qty);
这会将字符串转换为整数。 如果您想要真正健壮,您可以在添加之前检查NaN
的解析值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.