我正在尝试对一个动态数组求和。但出于某种原因,这些数字并没有相加,而是并排显示。我正在尝试做 1+2+3+4+5。但我的输出最终是 012345 而不是 15。
var userInput = -1;
var totalinputs = [];
var sum = 0;
var j = 0;
While(userInput != 999)
{
userInput = window.prompt("Enter a test score, or 999 to end the program");
if(userInput <= 100 && userInput >= 0)
{
totalInputs[j] = userInput;
j++;
}
}
$("lastScore").value = totalInputs[j-1];
for(var i = 0; i < totalInputs.length; i++)
{
sum += totalInputs[i];
}
$("sumScores").value = sum;
因此,当提示出现时,我输入 1、2、3、4、5,同时在每次输入之间按回车键,然后我输入 999 以结束提示。输出结果为 012345 而不是 15。我尝试了多种选择,但不确定为什么要这样做。 $ 函数只返回
window.document.getElementById(theId);
最佳答案
替换为以下内容
for(var i = 0; i < totalInputs.length; i++)
{
sum += +totalInputs[i]; //this coerces string to number.
}
a = "1"
可以在 javascript 中转换为 a = 1
,只需编写 a = +a,这种类型的强制转换是 JS 的特性。
用户从提示框中输入的是一个字符串。因此,您面临这个问题。
关于javascript - 求和数组不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42172103/