js- 数组扁平化

36 阅读1分钟

递归 出递归的条件:不是数组 且 深度 <= depth初始值

const arr = [1, 2, 3, [4, 5, 6]]
function flat(arr, depth = 1) {
    let r_arr = []
    function rd(arr, cur_dep = 0) {
	arr.forEach((item) => {
            if (Array.isArray(item) && cur_dep <= depth) {
		cur_dep++
		rd(item, cur_dep)
            } else {
		r_arr.push(item)
            }
	})
    }
    rd(arr)
    return r_arr
}
console.log(flat(arr, 3))

简易代码

Array.prototype.reduce = function (cb) {
  const arr = this; //this就是调用reduce方法的数组
  let total = arr[0]; // 默认为数组的第一项
  for (let i = 1; i < arr.length; i++) {
    total = cb(total, arr[i], i, arr);
  }
  return total;
};