[英]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. 我对多维数组使用Array.prototype.join
方法,但得到的结果很奇怪。 I try to see the bottom implementation of Array.prototype.join
, it show me the native code 我尝试查看Array.prototype.join
的底部实现,它向我展示了本机代码
[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 12345678
but the actual output is 但实际输出是
123,4,56,7,8 123,4,56,7,8
.join
在每个元素上调用.toString()
以将其转换为字符串,并且Array.prototype.toString()
默认情况下将其所有元素与,
。
console.log([1, 2, 3].toString());
Like others already said, toString is called upon the array. 就像其他人已经说过的, toString在数组上被调用。 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. 将简单地将第一级元素连接在一起,对不是字符串的元素调用toString 。
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). 结果为123,4,56,7,8
,其中3,4,5
是第一个嵌套数组,而6,7,8
是第二个嵌套数组(具有多个元素)。 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(" - "));
The join
method also invoke toString()
on each element. join
方法还会在每个元素上调用toString()
。
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 数组上的toString
方法从不保留方括号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.