簡體   English   中英

為什么String()使JS中的數組變平?

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

當發現將String構造函數應用於數組時,我感到驚訝。

為什么這樣做。 這是展平數組的好方法嗎?

在Mac Chrome,Safari,Firefox上測試結果相同。

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

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

因為將數組轉換為字符串將調用.toString ,因此與調用.join()基本上相同,后者將對數組中的所有元素調用.toString ,然后用逗號將結果刪除。 因此,將數組遞歸地連接到字符串,結果看起來很平坦,因為沒有用於數組開始或結束的指示符。 這是逐步的轉換:

 [[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"

它不會修飾數組,而是從數組中產生一個字符串。 為了更好的選擇退房Array.flat或者,例如,一些圖書館像lodash flattern() (下划線Rambda )。

這不是將數組轉換為字符串的唯一方法。 JSON.stringify通常是首選:

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

它似乎“弄平”列表的原因是在整個數組上遞歸調用了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