在 JavaScript 中展開陣列到一行
假設,我們有如下數字巢狀陣列 −
const arr = [ [ 0, 0, 0, −8.5, 28, 8.5 ], [ 1, 1, −3, 0, 3, 12 ], [ 2, 2, −0.5, 0, 0.5, 5.3 ] ];
我們應當編寫一個 JavaScript 函式,它可以接受一個這樣的數字巢狀陣列。該函式應當將巢狀陣列中的所有數字組合形成一個字串。
在結果字串中,相鄰的數字用空格分隔,且相鄰兩個陣列的元素用逗號分隔。
示例
此程式碼將是 −
const arr = [
[ 0, 0, 0, −8.5, 28, 8.5 ],
[ 1, 1, −3, 0, 3, 12 ],
[ 2, 2, −0.5, 0, 0.5, 5.3 ]
];
const arrayToString = (arr = []) => {
let res = '';
for(let i = 0; i < arr.length; i++){
const el = arr[i];
const temp = el.join(' ');
res += temp;
if(i !== arr.length − 1){
res += ',';
}
};
return res;
};
console.log(arrayToString(arr));輸出
且在控制檯中的輸出將是 −
0 0 0 −8.5 28 8.5,1 1 −3 0 3 12,2 2 −0.5 0 0.5 5.3
廣告
資料結構
網路
關係型資料庫
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP