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
178 views
in Technique[技术] by (71.8m points)

javascript - How come this For Loop increments in this manner? (seems exponential)

Javascript newbie here. I'm self-studying and now learning For Loops at this stage. I'm playing around with it by tweaking simple examples from Youtube tutorials. There's one I made that puzzles me a bit:

for (i = 0; i <=7; i+=1) {
    console.log(i);
    i += i;
    console.log(i);
}

And it prints out this output

Given that I have two console.logs, I know that I need to look at two sets of numbers separately. The 0,1,3,7 and 0,2,6,14. Here I see some pattern in the results. The numbers increment by 2^0, then 2^1, then 2^2, then 2^3 etc

I've been stuck for a while making sense of this. But I really don't understand how my code causes that to happen. So I'd really appreciate any help to break the code down to explain the pattern.

question from:https://stackoverflow.com/questions/65835257/how-come-this-for-loop-increments-in-this-manner-seems-exponential

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

1 Answer

0 votes
by (71.8m points)

Unrolling the loop to illustrate what others have already pointed out in the comments. You are incrementing i via the loop increment (as you should) but then also doubling it inside the loop every time. Here is what is happening from the i perspective:

i = 0; // loop initialization
console.log(0);
i = 0 + 0;
console.log(0);
i = 0 + 1; // loop increment
console.log(1);
i = 1 + 1;
console.log(2);
i = 2 + 1; // loop increment
console.log(3);
i = 3 + 3;
console.log(6);
i = 6 + 1; // loop increment
// ...

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

...