gpt4 book ai didi

JavaScript 总返回 NaN

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:21:58 24 4
gpt4 key购买 nike

我正在尝试使用 JavaScript 对对象数组求和,但它没有显示 86 的预期结果,而是显示 NaN

注意:我无法编辑对象数组!

var objects = [{"ID":"--"},{"ID":"58"},{"ID":"28"}];

var sum = 0;
id = objects;
for (var i = 0; i < id.length; i++) {
sum += +id[i].ID;
}

document.getElementById('here').innerHTML = "<b>Total:</b>" + sum;
objects.forEach(function(key) {
var a = document.createElement("p");
a.innerHTML = key.ID;
document.getElementById('here').appendChild(a);
});
<div id="here"></div>

JsFiddle:https://jsfiddle.net/ru266x7m/

请注意,这不是 Object returning NaN when sum values 的副本因为我已经有了代码行 var sum = 0;

最佳答案

如果值为 isFinite,您可以插入一个检查.

if (isFinite(id[i].ID)) {
sum += +id[i].ID;
}

var objects = [{"ID":"--"},{"ID":"58"},{"ID":"28"}];

var sum = 0;
id = objects;
for (var i = 0; i < id.length; i++) {
if (isFinite(id[i].ID)) {
sum += +id[i].ID;
}
}

document.getElementById('here').innerHTML = "<b>Total: </b>" + sum;
objects.forEach(function(key) {
var a = document.createElement("p");
a.innerHTML = key.ID;
document.getElementById('here').appendChild(a);
});
<div id="here"></div>

关于JavaScript 总返回 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38410793/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com