huaLin
huaLin

Reputation: 107

How can I really understand the method of 'Array.prototype.join'

I use the method of Array.prototype.join for multidimensional array, but I get curious result. I try to see the bottom implementation of Array.prototype.join, it show me the native code

[1,2,3,4,5,6,7,8].join('')
[1, [2], [3, [4, [5]]], [6, [7, [8]]]].join('');

I expect the output of

[1,[2],[3,[4,[5]]],[6,[7,[8]]]].join('') 

to be

12345678

but the actual output is

123,4,56,7,8

Upvotes: 0

Views: 178

Answers (3)

3limin4t0r
3limin4t0r

Reputation: 21130

Like others already said, toString is called upon the array. However, by providing a separator it will only join the array on which you call the method with that separator.

[
  1, 
  [2], 
  [3, [4, [5]]], 
  [6, [7, [8]]]
].join("")

Will simply join the first level elements together, calling toString on elements that aren't a string.

1.toString() + "" +
 [2].toString() + "" +
 [3, [4, [5]]].toString() + "" +
 [6, [7, [8]]].toString()

Where the "" is the separator. Resulting in 123,4,56,7,8 where 3,4,5 is the first nested array and 6,7,8 the second (with more than 1 element). If you'd like to join the elements recursive you could create your own method.

Array.prototype.deepJoin = function (separator) {
  return this
    .map(e => Array.isArray(e) ? e.deepJoin(separator) : e)
    .join(separator);
};

var array = [1, [2], [3, [4, [5]]], [6, [7, [8]]]];

console.log(array.join());
console.log(array.deepJoin());
console.log(array.join(""));
console.log(array.deepJoin(""));
console.log(array.join(" - "));
console.log(array.deepJoin(" - "));

Upvotes: 2

deceze
deceze

Reputation: 522135

.join calls .toString() on each element to turn it into a string, and Array.prototype.toString() by default concatenates all its elements with a ,.

console.log([1, 2, 3].toString());

Upvotes: 4

Christian Vincenzo Traina
Christian Vincenzo Traina

Reputation: 10414

The join method also invoke toString() on each element.

You have

[2].toString() -> 2
[3, [4, 5]].toString() -> 3,4,5

And so on. The toString method on an array never preserves square parenthesis

Upvotes: 1

Related Questions