简体   繁体   English

为什么String()使JS中的数组变平?

[英]Why does String() flatten an Array in JS?

I was surprised to discover flattening behavior of String constructor when applied to an Array. 当发现将String构造函数应用于数组时,我感到惊讶。

Why does this work. 为什么这样做。 And is this a good way to flatten an Array? 这是展平数组的好方法吗?

Tested to same results on Mac Chrome, Safari, Firefox. 在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. 因为将数组转换为字符串将调用.toString ,因此与调用.join()基本上相同,后者将对数组中的所有元素调用.toString ,然后用逗号将结果删除。 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 ). 为了更好的选择退房Array.flat或者,例如,一些图书馆像lodash flattern() (下划线Rambda )。

It is not the only way to convert an array into a string. 这不是将数组转换为字符串的唯一方法。 Often JSON.stringify is preferred: JSON.stringify通常是首选:

 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: 它似乎“弄平”列表的原因是在整个数组上递归调用了String

 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]) ); 

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

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