手写数组扁平化

手写数组扁平化

问题描述:
输入深度数组例如[1, 2, [3, 4, 5, [6, 7]]]
输出[1,2,3,4,5,6,7] 变为一个数组且不改变原有顺序

代码演示:

//手写数组扁平化

function flat(arr) {
    
    
    const isDeep = arr.some(item => item instanceof Array); //判断数组是否是深度数组,
    if (!isDeep) {
    
    
        return arr;//不是深度数组直接返回结果
    } else {
    
    
        const res = Array.prototype.concat.apply([], arr);//是深度数组进行扁平化 
        return flat(res); //递归操作,如果拍一次还有深度数组就继续判断 直到没有深度数组直接返回结果跳出递归
    }
}
const res = flat([1, 2, [3, 4, 5, [6, 7]]])  //验证
console.log(res); 

输出结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Qingshan_z/article/details/119998995