谁能解释为什么这段代码连接而不是添加数值?

Can anyone explain why this code concatenates rather than adds the numerical values?

所以,首先,我知道这段代码很乱,请耐心等待,但谁能解释为什么在通过 parseInt() 后,它一直连接输入的信息而不是添加数值?

var sol = 0;
var n = 0;

while(n !== null)
{

parseInt(n = prompt("Please enter a number to be added onto stack"));
  if(n != null || n != NaN)
  {
    sol = parseInt(sol);
    sol += n;
  }

}
console.log(sol);

prompt() return一个字符串。

parseInt() 接受一个字符串并且 return 接受一个数字。

您没有对第一个 parseInt 的 return 值执行任何操作。这意味着 n 是一个字符串。因此,当您执行 sol += n 时,您是在将字符串和数字相加,而 javascript 假定您打算将字符串连接在一起,因为带有字符串和数字的数学没有任何意义。

您可能打算这样做:

n = parseInt(prompt("Please enter a number to be added onto stack"));