手撕算法(2)——object展平

38 阅读1分钟
function flat(arr) {
    const newArr = [];
    for (const item of arr) {
        Array.isArray(item)? newArr.push(...flat(item)) : newArr.push(item); 
    }
    return newArr;
};

Object.prototype.myFlat = function() {
    const newArr = [];
    for (const item of this) {
        Array.isArray(item)? newArr.push(...item.myFlat()) : newArr.push(item); 
    }
    return newArr;
};

function flatten(arr) {
    let newArr = [];
    for (const item of arr) {
        Array.isArray(item) ? (newArr = newArr.concat(flatten(item))) : newArr.push(item);
    }
    return newArr;
}
// 用例:
const a = [1, 2, [3, [5], 7], 10];
const res1 = flat(a);
console.log(res1);
const res2 = a.myFlat();
console.log(res2);
const res3 = flatten(a);
console.log(res3);