JavaScript 把数组扁平化的方法

使用 ES2019中的新特性 Array.prototype.flat()

const arr = [1,2,3,4,[10,20,30]]
const res = arr.flat()
console.info(res) // [1,2,3,4,10,20,30]

使用 reduce, 递归数组

const arr = [1,2,3,4,[10,20,30]]

function flatten(arr){
    let res = []
    arr.forEach(val=>{
        if(val instanceof Array){
            res = res.concat(flatten(val))
        }else{
            res.push(val)
        }
    })
    return res
}

const res = flatten(arr)
console.info(res) // [1,2,3,4,10,20,30]

使用 apply 和 Array.prototype.concat (只能处二维数组转换成一维数组)

  • concat的特性: [].concat(1) => [1]; [].concat([1,2,3]) => [1,2,3] 如果concat的val是数组就等于该数组,如果是单个值,则为[val]
  • 原理: apply方法会调用一个函数,
  • 第一个参数会作为被调用函数的this
  • 第二个参数(一个数组 或者 类数组对象)作为被调用对象的 arguments值 也就是说该数组的各个元素会依次成为北调用函数的各个参数
const children = [[1,2],3,4]
const v = ['a','b','c']
const b = Array.prototype.concat.apply(v, children)
console.info(b) // ["a", "b", "c", 1, 2, 3, 4]
posted @ 2020-07-21 16:59  荣光无限  阅读(158)  评论(0编辑  收藏  举报