4 回答
TA贡献1862条经验 获得超7个赞
您可能正在解析不是整数的东西。然后parseInt将无法工作并返回NaN。如果你将NaN求和,那么它将保持NaN,例如:
// working testcase:
const testArray = ['2', '3', '4'];
let total = 0;
for (value of testArray) {
total += parseInt(value);
}
// returns 9
console.log(total);
// your testcase:
const testArray2 = ['2', '3', 'notANumber'];
let total2 = 0;
for (value of testArray2) {
total2 += parseInt(value);
}
// returns NaN since we are adding 2 + 3 + NaN = NaN
console.log(total2);
因此解决方案是通过将NaN视为0来“否定”NaN:
// solution:
const myArray = ['2', '3', 'notANumber', '4'];
let total = 0;
for (value of myArray) {
// treat NaN, undefined or any falsey values as 0.
total += parseInt(value) || 0;
}
// returns 9
console.log(total);
要在代码中集成此概念,您将获得以下内容:
let total = 0;
$('.input-n-pro').each(() => {
let valueInString = $(this).val();
let actualValue = parseInt(valueInString) || 0;
total += actualValue;
});
TA贡献1850条经验 获得超11个赞
如果其中一个输入值为空,则parseInt返回NAN。因此,您可以使用IsNan函数更好地进行检查。如果输入为空而不是赋值0。例如;
var x = parseInt($('#abc')。val()); if(isNaN(x))x = 0;
添加回答
举报
