Array.reverse() seems to not work?

Array.reverse() seems to not work?
0

#1

Can anyone explain why this code behaves this way?

function reverseString(str) {
  var chars = str.split();
  chars.reverse();
  chars.join();
  return chars;
}

reverseString("dog");

Output is:
[“dog”]


#2

After the first line, chars is an array of one element [ ‘dog’ ]. Why? Because you did not specify a delimiter. See the split documentation for more information.

After the second line, chars is still an array of one element in reversed order, so it is just the same array [ ‘dog’ ]

After the third line, chars does not change, because the join function does not affect the array on which it is called. It returns a string of the joined array. See the join documentation for more information.

In the end, the function returns [ ‘dog’]


#3

Ah, so .split() on a string creates a single element array? I thought it split the string into an array of characters.

God I miss real Java. Never thought I would say that…

Thanks Randell


#4

To do that you would need to write str.split(’’)