简体   繁体   English

为什么 Array.prototype.join() 会展平任意深度的数组?

[英]Why does Array.prototype.join() flatten an array of any depth?

Messing around with some JavaScript and what I thought should have produced a bug happened to work out as intended.使用一些 JavaScript 和我认为应该产生错误的东西碰巧按预期工作。 [].join() seems to flatten a nested array of any depth. [].join()似乎可以展平任何深度的嵌套数组。

var arr = [['a'], ['b'], ['c']];
arr.join('-'); // => 'a-b-c'

And even var arr = [['a'], [[[[[[[[['b']]]]]]]]], ['c']];甚至var arr = [['a'], [[[[[[[[['b']]]]]]]]], ['c']]; returns the exact same result as above.返回与上面完全相同的结果。

Which is especially odd since it returns the expected (erroneous) behavior with objects:这特别奇怪,因为它返回对象的预期(错误)行为:

var arr = [{}, {}, {}];
arr.join('-'); // => '[object Object]-[object Object]-[object Object]'

Curious if this is a feature of the latest chrome (53.0.2785.116), intended, or a bug?想知道这是最新版 chrome (53.0.2785.116) 的一项功能、意图还是错误?

For each element in the array that's being joined, the first thing that happens is that the element is coerced to a string.对于要连接的数组中的每个元素,发生的第一件事是该元素被强制转换为字符串。 Something like就像是

[[[[["b"]]]]]

when coerced to a string will just be当被强制为字符串时将只是

"b"

So when you do the join, the constituent elements will be forced to be strings before the join process does its thing of gluing the elements together.因此,当您进行连接时,在连接过程将元素粘合在一起之前,组成元素将被强制为字符串。

This is a result of the default toString behavior on ['a'] resulting in 'a' .这是['a']上的默认toString行为导致'a' It follows that [['a']].toString() also results in 'a' .因此[['a']].toString()也会导致'a' Playing around with this in the console should make this clear.在控制台中玩这个应该清楚这一点。 You would see a difference if your arrays had multiple elements, because ['a', 'b'].toString() would result in 'a,b' .如果您的数组有多个元素,您会看到不同,因为['a', 'b'].toString()将导致'a,b'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM