jQuery object - Value = value + number - 不起作用?
jQuery object - Value = value + number - Doesn't work?
我正在尝试更新对象中的值并将其设置为当前值 + 另一个数字。因此,例如,如果对象的值为 5
,我希望它像这样更新:对象键:当前值 (5) + 7
container[response["id"]]["quantity"] += quantity;
console.log(container[response["id"]].attr("quantity"));
这就是我目前正在尝试的。我最终得到 57
而不是 12
。
有什么想法吗?
你得到一个字符串,+
和 string
将它们连接起来。首先使用 parseInt()
或 parseFloat()
解析数字而不是添加。
let number = parseInt(container[response["id"]]["quantity"]);
number += quantity;
container[response["id"]]["quantity"] = number;
问题是,response["id"]]["quantity"]
的值 return 是 string
。当您尝试使用 +
将数字添加到字符串时,它会连接它,例如 5 + 7
就是 57
。要解决这个问题,您必须使用 parseInt()
或 parseFloat()
将数字解析为 Int
或 Float
。例如:
let num = parseInt(container[response["id"]]["quantity"]);
num += quantity;
container[response["id"]]["quantity"] = num;
我正在尝试更新对象中的值并将其设置为当前值 + 另一个数字。因此,例如,如果对象的值为 5
,我希望它像这样更新:对象键:当前值 (5) + 7
container[response["id"]]["quantity"] += quantity;
console.log(container[response["id"]].attr("quantity"));
这就是我目前正在尝试的。我最终得到 57
而不是 12
。
有什么想法吗?
你得到一个字符串,+
和 string
将它们连接起来。首先使用 parseInt()
或 parseFloat()
解析数字而不是添加。
let number = parseInt(container[response["id"]]["quantity"]);
number += quantity;
container[response["id"]]["quantity"] = number;
问题是,response["id"]]["quantity"]
的值 return 是 string
。当您尝试使用 +
将数字添加到字符串时,它会连接它,例如 5 + 7
就是 57
。要解决这个问题,您必须使用 parseInt()
或 parseFloat()
将数字解析为 Int
或 Float
。例如:
let num = parseInt(container[response["id"]]["quantity"]);
num += quantity;
container[response["id"]]["quantity"] = num;