微不足道的循环需要一个解释 [英] trivial for-loop needs an explanation

查看:127
本文介绍了微不足道的循环需要一个解释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 i + = i i = i + i 的缩写,下面的代码

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

应输出:

  1。 0,因为0 + = 0 + 0(i = 0)
2. 2,因为0 + = 1 + 1(i = 2)
3.6,因为2 + = 2 + 2 i = 6)
4. 12,因为6 + = 3 + 3(i = 12)



然而,虽然控制台确实输出了1 - 3,即0,2和6的值,但我得到的值为14,不是我预测的值(在执行for循环之前已经输入了第1行至第4行)for循环会输出(= 12 )。
我在这里解释错了什么?



代码本身显然没有趣味,但是我很好奇为什么它的工作方式是这样。 >解决方案

问题在于你正在更新循环内部的 i 以及循环本身。这意味着你需要查看两个更新,看看 i 真的发生了什么。以下是展开的步骤:

$ p $ for(var i = 0; i <= 10; i ++){...

// i = 0在这里
console.log(i + = i);
//记录0 + = 0(0)
//现在我将增加到1
console.log(i + = i);
//记录1 + = 1(2)
//将i增加到3
console.log(i + = i);
//记录3 + = 3(6)
//将i增加到7
console.log(i + = i);
//记录7 + = 7(14)
//将i增加到15
// ...等
+ = 也正在更新 i code>>循环内部,而不仅仅是从 ++ 递增器。


Since i += i is an abbreviation for i = i + i, the following code

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

should output:

1. 0, because  0 += 0 + 0 (i = 0)
2. 2, because  0 += 1 + 1 (i = 2)
3. 6, because  2 += 2 + 2 (i = 6)
4. 12, because 6 += 3 + 3 (i = 12)

However, although the console does output the values of 1. - 3., namely, 0, 2, and 6, correctly, the value that I get for 4., which is 14, is not the value that I predicted (the lines 1. - 4. above were typed out before the for-loop was executed) the for-loop would output (=12). What am I interpreting wrong here?

The code itself is evidently uninteresting, but nonetheless I am curious why it works the way it does.

解决方案

The problem is that you are updating i inside the loop as well as for the loop itself. This means you need to look at both updates to see what really happens to i. Here are the steps unrolled:

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

// i = 0 here
console.log(i += i);
// logged 0 += 0 (0)
// now i will be incremented to 1
console.log(i += i);
// logged 1 += 1 (2)
// increment i to 3
console.log(i += i);
// logged 3 += 3 (6)
// increment i to 7
console.log(i += i);
// logged 7 += 7 (14)
// increment i to 15
// ... etc

It looks like you just missed the fact that += is also updating the i inside the loop, not just from the ++ incrementor.

这篇关于微不足道的循环需要一个解释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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