[英]how i+=i works in a foor loop?
i wanted a for loop that sums a number 'i' with all previous numbers, for example: if i=5 then i want the loop to calculate the sum (5+4+3+2+1+0), then i tested this code which has returned some strange numbers:我想要一个将数字'i'与所有先前数字相加的for循环,例如:如果i = 5,那么我希望循环计算总和(5 + 4 + 3 + 2 + 1 + 0),然后我测试这段代码返回了一些奇怪的数字:
//-----------i<5 for(i=0; i<5; i++){ i += i; } console.log(i += i) //---------i<6 for(i=0;i<6;i++){ i += i; } console.log(i += i)
it had returned the same value for different 'i':它为不同的“i”返回了相同的值:
//for i <5
14
//for i < 6
14
That's because they both stop when i
reaches value of 7. Let's go over every single iteration, shall we?那是因为当
i
值达到 7 时它们都会停止。让我们在每次迭代中都使用 go,好吗?
During first iteration of the loop you:在循环的第一次迭代期间,您:
i=0
, then you add two zeros together with i+=i
, and finally increase it by 1 via i++
, you end up with i=1
i=0
开始,然后将两个零与i+=i
一起添加,最后通过i++
将其增加 1,最终得到i=1
During second iteration of the loop you:在循环的第二次迭代中,您:
i=1
, they you add two 1s together with i+=i
, and finally increase it by 1 via i++
, you end up with i=3
i=1
开始,他们将两个 1 与i+=i
相加,最后通过i++
将其增加 1,最终得到i=3
During final iteration of the loop you:在循环的最终迭代期间,您:
i=3
, they you add two 3s together with i+=i
, and finally increase it by 1 via i++
, you end up with i=7
i=3
开始,他们将两个 3 与i+=i
相加,最后通过i++
将其增加 1,最终得到i=7
Finally the console.log(i+=i)
adds two 7s together and you get 14.最后,
console.log(i+=i)
将两个 7 加在一起,得到 14。
Both loops stop at the 3rd iteration when i reaches the value of 7当 i 达到 7 的值时,两个循环都在第 3 次迭代中停止
The problem is you are increasing i
two times in a loop.问题是您在循环中将
i
增加了两次。 One with i++
and second with i += i
(meaning doubling i
)一个带有
i++
,第二个带有i += i
(意味着加倍i
)
Now lets see how i
changes in each iteration现在让我们看看
i
在每次迭代中如何变化
i = 0;
//First iteration
i = 0(i += i)
i = 1(i++)
//Second iteration
i = 2(i += i)
i = 3(i++)
//Third
i = 6(i += i)
i++ (i = 7)
So the loop will exit because 7 > 5. So the last of i
7
in both the cases so it gives same value for both loops所以循环将退出,因为 7 > 5。所以在这两种情况下
i
7
的最后一个,所以它为两个循环提供相同的值
Note: Don't ever assign variables to values like that.注意:永远不要将变量分配给这样的值。 Always use keywords
let
(if you wanna change the variable afterwards).始终使用关键字
let
(如果您想在之后更改变量)。 const
(if you don't want to change variable afterwards). const
(如果您不想在之后更改变量)。 Also try to avoid var
也尽量避免
var
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.