递归函数,最后是一个一维数组后,怎么进行下一步

function flatten(a, r) {
    if (!r) {
        r = [];
    }
    for (var i = 0; i < a.length; i++) {
        if (a[i].constructor == Array) {
            flatten(a[i], r);
        } else {
            r.push(a[i]);
        }
    }
    return r;
}

flatten([[1, 2],[3, 4, 5], [6, 7, 8, 9,[11,12,[12,13,[14]]]],10]);
// =>[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]
阅读 2.4k
2 个回答

参考:开开心心机试题

var flatten = function(array) {
    return array.reduce(function(previous, i) {
        if (Object.prototype.toString.call(i) !== '[object Array]') {
            return (previous.push(i), previous);
        }
        return (Array.prototype.push.apply(previous, flatten(i)), previous);
    }, []);
};

【】里多维还是一维数组,都可以用索性值来确定

推荐问题
宣传栏