2
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!

1
  • 2
    Could it be that you're looking for x.reverse()? Commented May 17, 2014 at 19:04

3 Answers 3

2
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']
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.