简体   繁体   中英

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. [].join() seems to flatten a nested array of any depth.

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

And even 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?

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' . It follows that [['a']].toString() also results in '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' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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