简体   繁体   English

为什么++ i在for循环之前不递增i?

[英]why does ++i not increment i before for loop?

So the following two functions print out the same exact results. 因此,以下两个函数可以打印出相同的准确结果。

console.log("i++");
 for (i=1; i<=3; i++) {
  console.log(i); // 1, 2
}
console.log("++i");
for (i=1; i<=3; ++i) {
  console.log(i); // 1, 2
}

This very counter intuitive as I'm specifically asking to post-increment one and per-increment the other. 这与我的直觉非常相反,我特别要求后增加一个,然后再增加一个。 It would be very desirable behavior to increment the value before the run inside the for loop. 在for循环内运行之前增加值将是非常理想的行为。 Is this behavior consistent?, Is this javascript specific or is this the standard behavior across programming languages that use ++i, i++ syntax and for loops? 这种行为是一致的吗?,这是javascript特定的还是这是使用++ i,i ++语法和for循环的编程语言的标准行为?

The third expression in the for loop header is evaluated after each iteration. for循环标题中的第三个表达式在每次迭代进行求值。 Thus: 从而:

  1. i is initialized to 1 i被初始化为1
  2. The loop test expression, i <= 3 , is evaluated (and found to be true ) 对循环测试表达式i <= 3进行求值(发现为true
  3. The loop body is executed 循环体被执行
  4. i++ or ++i happens i++++i发生了

Except for the minor syntax differences, that's exactly what would have happened in a C program in 1976. 除了语法上的微小差异外,这正是1976年C程序中发生的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM