美文网首页
ES-2019 新属flat()让你毫不费力的碾平多维数组

ES-2019 新属flat()让你毫不费力的碾平多维数组

作者: WilliamerTso | 来源:发表于2019-02-15 10:55 被阅读0次

递归地将数组展平到指定的深度并返回一个新数组。

Array.prototype.flat()

Syntax(语法): Array.prototype.flat(depth)
depth(深度)  默认值为一,可以无限延展至待碾平的数组的最深度

实例

const numbers = [1, 2, [3, 4, [5, 6]]];
// Considers default depth of 1
numbers.flat(); 
> [1, 2, 3, 4, [5, 6]]
// With depth of 2
numbers.flat(2); 
> [1, 2, 3, 4, 5, 6]
// Executes two flat operations
numbers.flat().flat(); 
> [1, 2, 3, 4, 5, 6]
// Flattens recursively until the array contains no nested arrays
numbers.flat(Infinity)
> [1, 2, 3, 4, 5, 6]

相关文章

网友评论

      本文标题:ES-2019 新属flat()让你毫不费力的碾平多维数组

      本文链接:https://www.haomeiwen.com/subject/wqqpeqtx.html