翻譯不完整。請協助 翻譯此英文文件。
這是一個實驗中的功能
此功能在某些瀏覽器尚在開發中,請參考兼容表格以得到不同瀏覽器用的前輟。
flat() 函數以遞迴方式將特定深度的子陣列重新串接成為一新的陣列
{{EmbedInteractiveExample("pages/js/array-flatten.html")}}
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
語法
var newArray = arr.flat([depth]);
參數
depth選擇性- 指定巢狀陣列展開的深度。預設為1。
回傳值
函數將會回傳一個由原先陣列的子陣列串接而成的新陣列。
範例
展開巢狀陣列
var arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] var arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] var arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6]
當遭遇空元素時
flat()函數會自動清除陣列中空的元素
var arr4 = [1, 2, , 4, 5]; arr4.flat(); // [1, 2, 4, 5]
替代方案
reduce 與 concat
var arr1 = [1, 2, [3, 4]]; arr1.flat(); //展開單層陣列 arr1.reduce((acc, val) => acc.concat(val), []);// [1, 2, 3, 4]
//欲展開更深層的巢狀結構請使用reduce與concat的遞迴
function flattenDeep(arr1) {
return arr1.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}
flattenDeep(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
//使用stack來實作非遞迴的展開
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flatten(input) {
const stack = [...input];
const res = [];
while (stack.length) {
// pop value from stack
const next = stack.pop();
if (Array.isArray(next)) {
// push back array items, won't modify the original input
stack.push(...next);
} else {
res.push(next);
}
}
//reverse to restore input order
return res.reverse();
}
flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
規範
| Specification | Status | Comment |
|---|---|---|
Array.prototype.flat proposal |
Candidate (3) |
瀏覽器相容性
The compatibility table in this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
| Desktop | Mobile | Server | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Basic support | Chrome Full support 69 | Edge No support No | Firefox Full support 62 | IE No support No | Opera Full support 56 | Safari Full support 12 | WebView Android Full support 69 | Chrome Android Full support 69 | Edge Mobile No support No | Firefox Android Full support 62 | Opera Android Full support 56 | Safari iOS Full support 12 | Samsung Internet Android No support No | nodejs No support No |
Legend
- Full support
- Full support
- No support
- No support
- Experimental. Expect behavior to change in the future.
- Experimental. Expect behavior to change in the future.