【问题标题】:Checking for numbers in a javascript array using inArray()使用 inArray() 检查 javascript 数组中的数字
【发布时间】:2015-07-24 09:36:28
【问题描述】:

我正在通过将产品列表添加到名为“oitems”的数组中来构建一个网络购物车。我正在使用 JSON 语法。以下函数旨在接受“quant”(产品数量)、“prod”(产品 id)、“name”(产品名称)、“price”(产品价格)和“order”(包含“oitems”的对象' 大批)。当有人单击产品旁边的“添加”按钮时,该功能会触发。

“prod”(产品 ID)范围为 1-30。我希望该函数在添加新产品时添加到“oitems”数组中,如果有人决定在添加“产品”后增加“产品”的“数量”,则更新产品的现有数量。它会这样做,直到“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.");
    }
}

【问题讨论】:

  • 你有小提琴或类似的东西让我们测试一下吗?
  • prod 实际上是一个数组吗?如果不是,你到底为什么认为$.inArray() 是正确的函数?请改用if(prod == order.oitems[x].product) {...}
  • 恐怕不行,对不起
  • @AnthonyGrist 非常感谢你......我觉得很愚蠢。你当然是对的,这就是答案

标签: javascript jquery arrays json


【解决方案1】:

我怀疑您将字符串传递给 updateOrder 函数的参数prod。当您在字符串上使用$.inArray() 时,它会将其作为单个字符的数组进行处理。

更具体地说,字符串“10”是两个字符的数组:1 和 0。如果您的项目数组中已经有产品 1,那么执行的测试之一将是:@ 987654324@,它将通过,因为“1”是构成字符串“10”的字符之一。

您可以并且应该将您的条件简化为以下内容:

if(prod == order.oitems[x].product) {...}

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2013-06-19
    • 1970-01-01
    相关资源
    最近更新 更多