Array.prototype.flat()

2021-04-22 14:31阅读 308

Array.prototype.flat()

定义:

flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。 —— MDN

flat(depth:number)函数接收一个 depth 展开深度,默认值为 1

[1,2,[3,[4,5]]].flat() // [1,2,3,[4,5]]
[1,2,[3,[4,5]]].flat(1) // [1,2,3,[4,5]]
[1,2,[3,[4,5]]].flat(2) // [1,2,3,4,5]

传0会怎么样呢

[1,2,[3,[4,5]]].flat(0) // [1,2,[3,[4,5]]]

传负数呢

[1,2,[3,[4,5]]].flat(-1) // [1,2,[3,[4,5]]]
[1,2,[3,[4,5]]].flat(-100) // [1,2,[3,[4,5]]]

由此可见, 当展开深度小于1时,则返回的新数组和原数组相同(非相等)

当需要把未知深度的数组拍成一维时可以用 Infinity

[1,2,[3,[4,5]]].flat(Infinity) // [1,2,3,4,5]
[1,2,[3,[4,5,[6]]]].flat(Infinity) // [1,2,3,4,5,6]

可以过滤empty值

[1,2,,4].flot() // [1,2,4]
[1,2,null,4].flot() // [1,2,null,4]

下面来手动实现下

递归实现
Array.prototype.myFlat = function(depth) {
  const result = []
  const loop = (_list, loopDepth = 1) => {
    _list.forEach(e => {
      if (Array.isArray(e) && depth >= loopDepth) {
        result.concat(loop(e, loopDepth+1))
      } else {
        result.push(e)
      }
    })
  }
  loop(this)
  return result
}
    
reduce实现
Array.prototype.myFlat = function (depth = 1) {
  const loop = (list, deep) => {
    if (deep < 1) return list
    return list.reduce((prev, current) => {
      const val = Array.isArray(current) ? loop(current, deep - 1) : current
      return prev.concat(val)
    },[])
  }
  return loop(this, depth)
}
Array.prototype.join 实现
[1,2,[3,[4,5]]].join() // '1,2,3,4,5'
Array.prototype.myFlat = function() {
  return this.join().split(',')
}

join的缺点:

  1. 只能处理 Array<string>
  2. 不支持层级
Array.prototype.toString 实现
[1,2,[3,[4,5]]].toString() // '1,2,3,4,5'
Array.prototype.myFlat = function() {
  return this.toString().split(',')
}

原理同join

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

标签
标签
标签