给定数组:
let arr = [1, [2, [3, [4, 5, [6, 7]]]], 8];
let str = JSON.stringify(arr);
实现其扁平化:
[1, 2, 3, 4, 5, 6, 7, 8]
var arr_flat = arr.flat(Infinity) // 参数:深度,默认为1
var arr_flat = str.replace(/(\[|\])/g, '').split(',')
str = str.replace(/(\[|\])/g, '')
str = `[${str}]`
var arr_flat = JSON.parse(str)
function MyFlat (arr) {
let result = [];
let fn = function (arr) {
for (var i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
fn(arr[i])
} else {
result.push(arr[i])
}
}
}
fn(arr)
return result;
}
var arr_flat = MyFlat(arr)
function reduceFlat (arr) {
let fn = function (arr) {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? fn(cur) : cur)
}, [])
}
return fn(arr)
}
var arr_flat = reduceFlat(arr)
function MyFlat (arr) {
while(arr.some(Array.isArray)) {
arr = [].concat(...arr)
}
return arr
}
var arr_flat = MyFlat(arr)