Javascript - “++ i”如何?工作? [英] Javascript - How does "++i" work?

查看:145
本文介绍了Javascript - “++ i”如何?工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试使用i ++和++ i后,我在'for'循环中使用时找不到它们的结果之间的差异。
例如:

  for(var i = 0; i< 10; ++ i){
console.log(i);
}

将产生:

  0 
1
2
3
4
5
6
7
8
9

不应该从1到10打印出数字,因为迭代器在 console.log(i)执行之前递增?

解决方案

在执行循环体之后执行增量步骤。鉴于<(p; b; c; c)<







$ b c $ c>

执行订单是

  a //初始化
b //条件 - 第一次迭代
d //循环体
c //increment
b //条件 - 第二次迭代
d //循环体
c //增量
...
b //条件 - 最后一次迭代 - 中断

所以在你的情况下:

  var i = 0; 
i< 10;
console.log(i); // 0
++ i;
i< 10;
console.log(i); // 1
++ i;
// ...
i< 10;

i ++ 和<$ c之间的差异$ c> ++ i 仅在您使用返回值执行某些操作时才有效。


After experimenting with the use of "i++" and "++i" I could not find a difference between their results when used in a 'for' loop. For example:

for (var i = 0; i < 10; ++i) {
    console.log(i);
}

would yield:

0
1
2
3
4
5
6
7
8
9

Shouldn't it be printing out the numbers from 1 to 10, as the iterator is being incremented before console.log(i) executes?

解决方案

The "increment step" is executed after the loop body is executed. Given

for (a;b;c) {
  d
}

the execution order is

a // initialize
b // condition - first iteration
d // loop body
c // "increment"
b // condition - second iteration
d // loop body
c // "increment"
...
b // condition - last iteration - break

So in your case:

var i = 0;
i < 10;
console.log(i); // 0
++i;
i < 10;
console.log(i); // 1
++i;
// ...
i < 10;

The difference between i++ and ++i is only relevant if you do something with the return value, which you don't.

这篇关于Javascript - “++ i”如何?工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆