手寫(xiě)es10數(shù)組的flat方法

關(guān)于 Array.prototype.flat

flat 方法會(huì)按照一個(gè)可指定的深度遞歸遍歷數(shù)組,并將所有元素與遍歷到的子數(shù)組中的元素合并為一個(gè)新數(shù)組返回??梢岳斫鉃槎嗑S數(shù)組降維。

語(yǔ)法

var newArray = arr.flat([depth]);

特性

  1. 參數(shù) depth,指定要提取嵌套數(shù)組的結(jié)構(gòu)深度,默認(rèn)值為 1;
  2. 參數(shù) depth 為 Infinity,可展開(kāi)任意深度的嵌套數(shù)組;
  3. 移除數(shù)組中的空項(xiàng)。

代碼實(shí)現(xiàn)

Array.prototype.flat = function(depth) {
    // 無(wú)層數(shù),設(shè)置為1
    if (depth === undefined) {
        depth = 1;
    }

    // 層數(shù)不是number,返回原數(shù)組
    if (typeof depth !== "number" || isNaN(depth)) {
        console.error("參數(shù)必須為number");
        return this;
    }

    // 層數(shù)<=0,返回原數(shù)組
    if (depth <= 0) {
        return this;
    }

    // 層數(shù)為某個(gè)正整數(shù)時(shí)
    function _flat(depth) {
        _array = _flatSingle(_array);
        depth--;
        if (depth > 0) {
            _flat(depth);
        }
    }

    // 層數(shù)為正無(wú)窮大時(shí)
    function _flatInfinity() {
        _array = _flatSingle(_array);

        for (let i = 0; i < _array.length; i++) {
            if (Array.isArray(_array[i])) {
                _flatInfinity();
                break;
            }
        }
    }

    // 單次降維,同時(shí)過(guò)濾空項(xiàng)
    function _flatSingle(array) {
        return array.reduce((pre, item) => {
            if (Array.isArray(item)) {
                item = item.filter(_item => _item !== null);

                return [...pre, ...item];
            }

            item !== null && pre.push(item);
            return pre;
        }, []);
    }

    function clone(data) {
        return JSON.parse(JSON.stringify(data));
    }

    let _array = clone(this);
    depth === Infinity ? _flatInfinity() : _flat(depth);
    return _array;
};

console.log([1, [1, 2]].flat("a")); // [1, [1, 2]]
console.log([1, [1, 2]].flat()); // [1, 1, 2]
console.log([1, [1, [1, 2]]].flat(2)); // [1, 1, 1, 2]
console.log([1, [1, [1, [1, 2]]]].flat(Infinity)); // [1, 1, 1, 1, 2]
console.log([1, [1, 2]].flat(0)); // [1, [1, 2]]
console.log([1, [1, 2]].flat(-2)); // [1, [1, 2]]
console.log([1, , [, 1]].flat()); // [1, 1]

參考文獻(xiàn)

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/flat

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容