美文网首页
数组flat实现

数组flat实现

作者: 蜻蜓路过风 | 来源:发表于2020-03-11 16:43 被阅读0次

利用数组的reduce和concat实现数组flat,并可传参

Array.prototype.flat = function(deep = 1) {
    if(typeof deep !== 'number') {
        throw new TypeError('深度参数必须为数字类型')
    }
    if(deep === 0) return this
    let arr1 = this
    return arr1.reduce((acc, val) => {
        console.log(deep)
        if(Array.isArray(val) && deep > 1) {
            console.log(acc)
            return acc.concat(val.flat(--deep))
        } else {
            return acc.concat(val)
        }
    }, []);// [1, 2, 3, 4]
}

相关文章

  • 数组flat实现

    利用数组的reduce和concat实现数组flat,并可传参

  • js中数组flat方法的使用和实现

    js中数组flat方法的使用和实现 定义 flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历...

  • 数组flat

    实现一个方法,能够把多重数组变成一个一维数组

  • 数组-flat

    描述 flat方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组元素合并为一个新数组返回 语法 ...

  • js函数实现:数组扁平化、防抖、节流、对象拷贝

    1.数组扁平化初探 ES6中数组的扩展引入了flat和flatMap:数组的flat方法: 数组的flatMap方...

  • 数组如何扁平化?

    1.有一个多维数组如下: 现在要将此数组变成一维数组,有多少种方法? 2.如何实现? 2.1 flat 注意:低版...

  • 手写源码-实现 flat 拍平数组

    forEach 循环实现 通过 concat 实现拍平通过 arguments.callee 实现递归(只能在严格...

  • flat

    js Array flat flat() 方法会递归到指定深度将所有子数组连接,并返回一个新数组 详细参考

  • 数组扁平化

    1. es6 flat 2.es6 ...拓展运算符 3.递归实现数组扁平化 4.reduce实现 5.whil...

  • 手写代码系列

    深拷贝 html转码 手写promise.all 有哪些实现数组扁平化的方法 原生js 运用flat方法 redu...

网友评论

      本文标题:数组flat实现

      本文链接:https://www.haomeiwen.com/subject/nkqhjhtx.html