user3516885
user3516885

Reputation: 29

javascript for loop order

var x = ["a", "b", "c"];
for(var i = 0; i < x.length; i++){

x[i] = x[2 - i];

}

My approach:
for i = 0 => x[0] = x[2] (which is "c", so replace "a" with "c")
for i = 1 => x[1] = x[1] (which is "b", so replace "b" with "b")
for i = 2 => x[2] = x[0] (which is "a" so replace "c" with "a")
for i = 3 test failed, stop.
so x = ["c", "b", "a"]

Why does the console return x as ["c","b","c"]? Could somebody please tell me whether I have completely misunderstood loop logic? Thank you!

Upvotes: 2

Views: 56

Answers (3)

lonesomeday
lonesomeday

Reputation: 237855

var x = ["a", "b", "c"];
for(var i = 0; i < x.length; i++){

x[i] = x[2 - i];

}

Let's write this code out longhand:

var x = ['a', 'b', 'c'];

x[0] = x[2]; // ['c', 'b', 'c']
x[1] = x[1]; // ['c', 'b', 'c']
x[2] = x[0]; // ['c', 'b', 'c']

The problem is that by the time you get to i = 2 you've already modified x[0] = x[2], so x[2] = x[0] unsurprisingly has no result.

You can use the Array#reverse method, I think:

var x = ['a', 'b', 'c'];
x.reverse(); // ['c', 'b', 'a']

Upvotes: 2

Adrian Toma
Adrian Toma

Reputation: 547

When i = 2, x[0] is "c" , you replaced it when "i" was 0. So it will be ["c","b","c"].

Upvotes: 0

Plato
Plato

Reputation: 11052

edit: Neat! Didn't know about Array.reverse(), that's definitely easier than below!

By the time the third iteration occurs, the first element has already been set to "c" in the first iteration.

The easiest way to do it is to simply make a second array for output:

var x = ["a", "b", "c"];
var y = new Array(x.length);
for(var i = 0; i < x.length; i++){
  y[i] = x[2 - i];
}
console.log(y)

Upvotes: 1

Related Questions