JavaScript: Array reverse and join is not working as expected for empty tokens in join() method

时间:2019-04-08 13:08:07

标签: javascript arrays

I am trying to reverse a string and applying join() method on the reversed contents in JavaScript. The join works properly when I use "-" or any other symbol in the join() method. But when I use just ("") or (" ") , it simply joining original array and not the reversed one. Please help me to understand the actual behavior.

Consider the below code.

var a = [1,2,3]; //actual array
console.log(a.reverse().join("-")); // working as expected. output: "3-2-1"
console.log(a.reverse().join(""));  //not working as expected. output:"123"

Thanks, Dhinesh

3 个答案:

答案 0 :(得分:4)

Reverse mutates original array

The reverse() method reverses an array in place. The first array element becomes the last, and the last array element becomes the first.

You can make a shallow copy in this case and than use reverse

var a = [1,2,3]; //actual array
console.log([...a].reverse().join("-")); // working as expected. output: "3-2-1"
console.log([...a].reverse().join("")); 

答案 1 :(得分:1)

reverse reverse the elements in the original array.

The reverse method transposes the elements of the calling array object in place, mutating the array, and returning a reference to the array.

var a = [1,2,3]; //actual array
console.log(a.reverse().join("-")); // working as expected. output: "3-2-1"
console.log(a.join(""));  //working as expected. output:"321"

答案 2 :(得分:0)

It's only a problem of working on the same array and doing two times the reverse operation. Let's try doing this:

var a = [1,2,3]; 
const reversedArr = a.reverse();
console.log(reversedArr.join("-")); 
console.log(reversedArr.join(""));