oneWorkingHeadphone oneWorkingHeadphone - 1 month ago 4x
Javascript Question

For statement returns unexpected value on last assignment

I'm trying to build a simple "cipher" to assign the letters in a string the value of a reversed alphabet (e.g. a=z b=y, etc..) I built a for statement that seems to work until the last call and instead of giving the reversed value instead gives the original value.

I commented out each line in the for statement and then worked through them one at a time to check their returns. The second to last statement (c = rev.indexOf(c);) give the value of 25, 24, 23 (as expected) so I don't understand why when it looks them up in the "letters" matrix it gives a return of a, b, c instead of z, y, x.

var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'y', 'x', 'z'];
var rev = letters.reverse();

var stringy = function(n){
ns = n.split("");
for (i = 0; i < n.length; i++){
c = ns[i];
c = rev.indexOf(c);
c = letters[c];



letters.reverse() doesn't just return the reversed array. It reverses the array in place.

If you check the contents of letters after letters.reverse() you'll see that the order has been reversed.

You can use .slice() to make a copy of the array, which you can then reverse:

var rev = letters.slice().reverse();