手写es10数组的flat方法

关于 Array.prototype.flat

flat 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。可以理解为多维数组降维。

语法

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

特性

  1. 参数 depth,指定要提取嵌套数组的结构深度,默认值为 1;
  2. 参数 depth 为 Infinity,可展开任意深度的嵌套数组;
  3. 移除数组中的空项。

代码实现

Array.prototype.flat = function(depth) {
    // 无层数,设置为1
    if (depth === undefined) {
        depth = 1;
    }

    // 层数不是number,返回原数组
    if (typeof depth !== "number" || isNaN(depth)) {
        console.error("参数必须为number");
        return this;
    }

    // 层数<=0,返回原数组
    if (depth <= 0) {
        return this;
    }

    // 层数为某个正整数时
    function _flat(depth) {
        _array = _flatSingle(_array);
        depth--;
        if (depth > 0) {
            _flat(depth);
        }
    }

    // 层数为正无穷大时
    function _flatInfinity() {
        _array = _flatSingle(_array);

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

    // 单次降维,同时过滤空项
    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]

参考文献

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。