简体   繁体   中英

Why does String() flatten an Array in JS?

I was surprised to discover flattening behavior of String constructor when applied to an Array.

Why does this work. And is this a good way to flatten an Array?

Tested to same results on Mac Chrome, Safari, Firefox.

String(['a', 'b', ['c', 'd', ['e', 'f']]])

=> "a,b,c,d,e,f"

Because converting an array to a string will call .toString which is basically the same as calling .join() , which will call .toString onto all elements in the array, and then delemit the result with a comma. Therefore the arrays get recursively joined to a string, the result looks flattened as there is no indicator for the start or end of the array. Here is the conversion step by step:

 [[1, 2, 3], [1, 2, 3]].toString()
 [1, 2, 3].toString() + "," + [1, 2, 3].toString()
 (1 + "," + 2 + "," + 3) + "," + (1 + "," + 2 + "," + 3)
 "1,2,3" + "1,2,3"
 "1,2,3,1,2,3"

It doesn't flattern an array, it makes a string out of an array. For better options check out Array.flat or, for example, some libraries like lodash flattern() (or Underscore or Rambda ).

It is not the only way to convert an array into a string. Often JSON.stringify is preferred:

 const arr = [1,[2,[3]]]; console.log(JSON.stringify(arr)); 

The reason why it seems to 'flatten' the list is that it String is being called recursively on the whole array:

 const arr = [1,[2,[3]]]; console.log( String(arr) ); console.log( String(arr[0]), '+ , +', String(arr[1]) ); console.log( String(arr[0]), '+ , +', String(arr[1][0]), '+ , +', String(arr[1][1]) ); 

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