【问题标题】:jQuery object - Value = value + number - Doesn't work?jQuery 对象 - 值 = 值 + 数字 - 不起作用?
【发布时间】:2017-09-28 07:24:29
【问题描述】:

我正在尝试更新对象中的值并将其设置为当前值 + 另一个数字。例如,如果一个对象的值为5,我希望它像这样更新:对象键:当前值(5) + 7

container[response["id"]]["quantity"] += quantity;          
console.log(container[response["id"]].attr("quantity"));

这是我目前正在尝试的。我最终得到57 而不是12

有什么想法吗?

【问题讨论】:

    标签: javascript jquery object numbers add


    【解决方案1】:

    你得到一个字符串,+strings 连接它们。首先使用parseInt()parseFloat() 解析为数字而不是添加。

    let number = parseInt(container[response["id"]]["quantity"]);
    number += quantity;
    container[response["id"]]["quantity"] = number;
    

    【讨论】:

    • 没用,恐怕.. 只是以 1 - 11 - 111 - 1111 等结束。
    • 我不明白。你提供你使用 5 + 7 得到的东西
    • 啊,是的,只是一个例子:) 5 + 7,我仍然得到 57 - 577 - 5777 - 5777
    • 你的数量也是一个数字吗?有一种情况,其中一种是字符串。确保两者都是数字类型
    • 稍微调整一下我的脚本,这实际上是正确的解决方案!谢谢! :-)
    【解决方案2】:

    问题是,response["id"]]["quantity"] 返回的值是string。当您尝试使用+ 将数字添加到字符串时,它会将其连接起来,例如5 + 757。为了解决这个问题,您必须使用parseInt()parseFloat() 将数字解析为IntFloat。例如:

    let num = parseInt(container[response["id"]]["quantity"]);
    num += quantity;
    container[response["id"]]["quantity"] = num;
    

    【讨论】:

      猜你喜欢
      • 2020-12-19
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 2022-07-05
      • 1970-01-01
      • 2019-02-05
      • 2015-02-12
      相关资源
      最近更新 更多