Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

javascript - 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<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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's because they both stop when i reaches value of 7. Let's go over every single iteration, shall we?

During first iteration of the loop you:

  • start with 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

During second iteration of the loop you:

  • start with 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

During final iteration of the loop you:

  • start with 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

Finally the console.log(i+=i) adds two 7s together and you get 14.

Both loops stop at the 3rd iteration when i reaches the value of 7


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...