javascript for loop order -


var x = ["a", "b", "c"]; for(var = 0; < x.length; i++){  x[i] = x[2 - i];  }  approach: = 0 => x[0] = x[2] (which "c", replace "a" "c") = 1 => x[1] = x[1] (which "b", replace "b" "b") = 2 => x[2] = x[0] (which "a" replace "c" "a") = 3 test failed, stop. x = ["c", "b", "a"] 

why console return x ["c","b","c"]? please tell me whether have misunderstood loop logic? thank you!

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

let's write 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 time i = 2 you've modified x[0] = x[2], x[2] = x[0] unsurprisingly has no result.

you can use array#reverse method, think:

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

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -