js 数组扁平化 数组展平

1 flat

let arr = [1, [2, 3], [4, [5, [6, 7]]]]; 
let ret = arr.flat(Infinity);
console.log(ret);

2 toString + split

let arr = [1, [2, 3], [4, [5, [6, 7]]]]; 
let ret = arr.toString().split(',').map(Number); 
console.log(ret);

3 join + split

let arr = [1, [2, 3], [4, [5, [6, 7]]]]; 
let ret = arr.join().split(',').map(Number); 
console.log(ret);

4 join + split

let arr = [1, [2, 3], [4, [5, [6, 7]]]]; 
const flatten=(arr)=>{ 
    return [].concat(...arr.map(item=>Array.isArray(item)? flatten(item):item) ) 
 } 
 flatten(arr);

你可能感兴趣的:(javascript,javascript,前端)