SOURCE

let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

function sum(arr) {
    return arr.reduce(((prev, cur) => { return prev + cur }), 1)
}

console.log(sum(arr1))

//多维数组变成自定义一维数组
let arr2 = [1, 2, [3, 4, [5, 6, 7, 8], 9], 10, [11], 12];
// flat 参数默认数组维度
console.log(arr2.flat());

function flat(arr, n) {
    let newArr = [];
    n = n || 2; //目标层级
    let count = 0; //记录当前层级
    function Recursive(arr) {
        arr.forEach(item => {
            if (Array.isArray(item)) {
                Recursive(item)
            } else {
                newArr.push(item);
            }
        })
    }
    Recursive(arr)
    return newArr
}

console.log(flat(arr2))


// Array.prototype.myFlat = function (n) {
//     if (!this instanceof Array) {
//         throw new Error("not a array")
//     }
//     n = n || 2;

//     let arr = this || [];


//     console.log(flatRecursive(arr))
//     return flatRecursive(arr);
// }

// arr2.myFlat()

// reduce实现数组降维
function flat2(arr) {
    return arr.reduce((prev, next) => {
        return prev.concat(Array.isArray(next) ? flat2(next) : next)
    }, [])
}

console.log(flat2(arr2))

console 命令行工具 X clear

                    
>
console