/*
Array.prototype.flat():返回一个新数组,对原数据没有影响
1.不传参数:默认扁平化一层
2.参数<=0,不变
3.Infinity参数:无论多少层都转化为一维数组
4.如果有空位,会跳过空位
*/
const arr = [1, [2, 3, [3.1, 3.2, [3, 3]]], [4], 5, 6, "string", 7]
console.log(arr.flat(Infinity))
const flat = arr => {
return arr.reduce((pre, cur) => {
return pre.concat(Array.isArray(cur) ? flat(cur) : cur);
}, []);
};
console.log(flat([1, 2, 3, 4, [1, 2, 3, [1, 2, 3, [1, 2, 3]]], 5, "string", { name: "xxx" }]))
// [1, 2, 3, 4, 1, 2, 3, 1, 2, 3, 1, 2, 3, 5, "string", { name: "弹铁蛋同学" }];
console