We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
flattenDeep([1, [2, [3, [4]], 5]]); // [1, 2, 3, 4, 5]
利用 Array.prototype.flat
ES6 为数组实例新增了flat方法,用于将嵌套的数组变成一维数组。该方法返回一个新数组,对原数组没有影响。
flat
新数组
flat默认只会 “拉平” 一层,如果想要 “拉平” 多层的嵌套数组,需要给flat传递想要拉平的层数。
/** * deepLength 想要拉平的层数 */ function flattenDeep(arr, deepLength) { return arr.flat(deepLength); } console.log(flattenDeep([1, [2, [3, [4]], 5]], 3));
当传递的整数大于数组嵌套的层数时,会将数组拉平为一维数组,JS能表示的最大数字为Math.pow(2, 53) - 1,因此我们可以这样定义 flattenDeep 函数
大于
Math.pow(2, 53) - 1
function flattenDeep(arr) { // 大多时候我们不会嵌套这么多层级 return arr.flat(Math.pow(2,53) - 1); } console.log(flattenDeep([1, [2, [3, [4]], 5]]));
利用 reduce、concat和递归实现
function flattenDeep(arr){ return arr.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []); } console.log(flattenDeep([1, [2, [3, [4]], 5]]));
The text was updated successfully, but these errors were encountered:
No branches or pull requests
实现效果
实现方法
ES6 为数组实例新增了
flat
方法,用于将嵌套的数组变成一维数组。该方法返回一个新数组
,对原数组没有影响。flat
默认只会 “拉平” 一层,如果想要 “拉平” 多层的嵌套数组,需要给flat
传递想要拉平的层数。当传递的整数
大于
数组嵌套的层数时,会将数组拉平为一维数组,JS能表示的最大数字为Math.pow(2, 53) - 1
,因此我们可以这样定义 flattenDeep 函数The text was updated successfully, but these errors were encountered: