SOURCE

// 数组展开--2022-06-15

let arr = [1, ['2', [3, 4, 5]]];

// 方法1:最普通的递归,
let result1 = []
function flatten1(arr) {
    for (var i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
            flatten1(arr[i])
        }
        else {
            result1.push(arr[i])
        }
    }
    return result1
}
console.log(flatten1(arr), 'flatten1');

// 方法2:封装方法1
function flattenNormal(arry) {
    let result2 = []

    function flatten2(arr) {
        for (var i = 0; i < arr.length; i++) {
            if (Array.isArray(arr[i])) {
                flatten2(arr[i])
            }
            else {
                result2.push(arr[i])
            }
        }
    }
    flatten2(arry)
    return result2
}

console.log('flattenNormal',flattenNormal(arr))


// 方法3:普通递归实现-concat
function flatten(arr) {
    var result = []
    for (var i = 0; i < arr.length; i++) {
        if (Array.isArray(arr[i])) {
            result = result.concat(flatten(arr[i]))
        }
        else {
            result.push(arr[i])
        }
    }
    return result
}

console.log('flatten3',flatten(arr));

console 命令行工具 X clear

                    
>
console