Chrome locks with correct Javascript loop

Asked

Viewed 617 times

0

I’m trying to run the following code, only I can’t! It’s like the browser stops working.

var scores = [60, 50, 60, 58, 54, 54,
58, 50, 52, 54, 48, 69,
34, 55, 51, 52, 44, 51,
69, 64, 66, 55, 52, 61,
46, 31, 57, 52, 44, 18,
41, 53, 55, 61, 51, 44];

for (var i=0; i < scores.length; i = i++) {
    console.log("Buble Solution #" + i + " Score: " + scores[i]);
}

But when I try to perform the synonym with the i = i + 1, works!

1 answer

6


When you use i++ two things happen:

  • the i increases in value (sum +1)
  • this action returns the i initial

For, returns the i initial (before adding 1 more).

Try:

var i = 0;
alert(i++); // 0
alert(i); // 1

I mean, in your loop you’re doing the i take the return value of i++, that is to say: i = i++, what is the same as saying i = 0... eternally.

Hence the problem.

When you use i = i + 1 It’s no longer a problem, and when you use only i++ (unused i =) there’s no problem either.

  • 2

    Very good! Thank you! Helped me a lot!

  • or ++i which increments the variable and then returns the new value. I still believe that in your situation, use forEach would be more performatic..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.