counter = 1;
time = 60;
while (counter < time) {
console.log(counter);
counter += 1;
}
为什么REPL中的代码值大于1到60
虽然下面的REPL中的代码输出为1到59:
counter = 1;
time = 60;
while (counter < time) {
console.log(counter);
counter++;
}
我测试了REPL中的两个代码。
在两种情况下,循环仅输出1
至59
,但是,节点REPL也会输出最后计算的表达式的结果。
[在第一种情况下,最后计算的表达式为(counter += 1)
,其计算为计数器(60)的新值,而在第二种情况下,最后一次计算的表达式为(counter++)
,其计算为计数器增量前的值( 59)。如果仔细看,您会发现在第二个版本中,59
在输出中出现了两次(由console.log
打印一次,由REPL打印一次。)>
如果您不确定,请尝试以下方法:
counter = 1;
time = 60;
while (counter < time) {
console.log(counter);
counter += 1;
'Hello!';
}
这两段代码的行为完全相同。 a++;
作为语句将与a += 1;