我正在为一个产品列表构建一个Web购物车,方法是将它们添加到一个名为'oitems'的数组中。我正在使用JSON语法。以下功能旨在接受'quant'(产品数量),'产品ID','名称'(产品名称),'价格'(产品价格)和'订单'(包含'oitems的对象' '阵列)。当有人点击产品旁边的“添加”按钮时,功能就会触发。
'prod'(产品ID)范围为1-30。我希望在添加新产品时将该功能添加到'oitems'数组中,如果某人决定在添加新产品后决定增加'prod'的'quant',则更新产品的现有数量。这样做,直到'prod'数字达到'10'并且我不知道为什么。我认为它在'1'和'10'之间感到困惑,但我不知道如何解决这个问题。有什么想法吗?
function updateOrder(quant, prod, name, price, order) {
var cnt = 0;
//loop through the array to see what we have
$.each(order.oitems, function(x, y) {
//see if the product is already in the array
if ($.inArray(prod, order.oitems[x].product) !== -1) {
// product is already in the cart, update with new quantities
order.oitems.splice(x, 1, {
"quantity": quant,
"product": prod,
"name": name,
"price": price
});
cnt++;
feedback("You already have this product. The quantities have been updated.");
}
});
if (cnt == 0) {
order.oitems.push({
"quantity": quant,
"product": prod,
"name": name,
"price": price
});
feedback("This product has been added to your order.");
}
}
答案 0 :(得分:1)
我怀疑您将字符串传递给updateOrder函数的参数prod
。在字符串上使用$.inArray()
时,它会将其作为单个字符数组进行处理。
更具体地说,字符串“10”是两个字符的数组:1和0.如果您的项目数组中已经有产品1
,那么执行的其中一个测试将是这个:$.inArray("10", "1")
,它将通过,因为“1”是形成字符串“10”的字符之一。
您可以 - 并且应该 - 将您的情况简化为以下内容:
if(prod == order.oitems[x].product) {...}