As mentioned by others, the toString function is invoked on the array. However, if you specify a separator, it will only join the array you are calling the method on with that particular separator.
[
1,
[2],
[3, [4, [5]]],
[6, [7, [8]]]
].join("")
This code snippet will concatenate the elements of the first level together, converting non-string elements to strings using the toString method.
1.toString() + "" +
[2].toString() + "" +
[3, [4, [5]]].toString() + "" +
[6, [7, [8]]].toString()
The empty string ""
serves as the separator. The result will be 123,4,56,7,8
, where 3,4,5
represents the first nested array and 6,7,8
corresponds to the second nested array (which contains more than one element). If you want to join the elements recursively, you can define your own custom 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(" - "));