试一试
const arr1 = [0, 1, 2, [3, 4]];
console.log(arr1.flat());
// expected output: Array [0, 1, 2, 3, 4]
const arr2 = [0, 1, [2, [3, [4, 5]]]];
console.log(arr2.flat());
// expected output: Array [0, 1, 2, Array [3, Array [4, 5]]]
console.log(arr2.flat(2));
// expected output: Array [0, 1, 2, 3, Array [4, 5]]
console.log(arr2.flat(Infinity));
// expected output: Array [0, 1, 2, 3, 4, 5]
语法
js
flat()
flat(depth)
参数
depth可选-
指定应将嵌套数组结构展平多深的深度级别。默认为 1。
返回值
一个将子数组元素连接到其中的新数组。
描述
flat() 方法是 复制方法。它不会更改 this,而是返回一个 浅拷贝,其中包含与原始数组相同的元素。
如果正在展平的数组是 稀疏数组,则 flat() 方法会删除空槽。例如,如果 depth 为 1,则会忽略根数组和第一级嵌套数组中的空槽,但更深层嵌套数组中的空槽会与数组本身一起保留。
flat() 方法是 通用的。它只期望 this 值具有 length 属性和整数键属性。但是,它的元素必须是数组才能进行展平。
示例
展平嵌套数组
js
const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
在稀疏数组上使用 flat()
flat() 方法会删除数组中的 空槽
js
const arr5 = [1, 2, , 4, 5];
console.log(arr5.flat()); // [1, 2, 4, 5]
const array = [1, , 3, ["a", , "c"]];
console.log(array.flat()); // [ 1, 3, "a", "c" ]
const array2 = [1, , 3, undefined, ["a", , ["d", , "e"]], null];
console.log(array2.flat()); // [ 1, 3, undefined, "a", ["d", empty, "e"], null ]
console.log(array2.flat(2)); // [ 1, 3, undefined, "a", "d", "e", null ]
在非数组对象上调用 flat()
flat() 方法读取 this 的 length 属性,然后访问键小于 length 的每个非负整数键属性。如果元素不是数组,则直接将其附加到结果中。如果元素是数组,则根据 depth 参数进行展平。
js
const arrayLike = {
length: 3,
0: [1, 2],
// Array-like objects aren't flattened
1: { length: 2, 0: 3, 1: 4 },
2: 5,
3: 3, // ignored by flat() since length is 3
};
console.log(Array.prototype.flat.call(arrayLike));
// [ 1, 2, { '0': 3, '1': 4, length: 2 }, 5 ]
规范
| 规范 |
|---|
| ECMAScript® 2026 语言规范 # sec-array.prototype.flat |
浏览器兼容性
加载中…