Object.defineProperty() 方法会直接在一个对象上定义一个新属性,或者修改一个对象的现有属性, 并返回这个对象,所以用Object.defineProperty给Array添加一个flat()方法

Object.defineProperty(Array.prototype, 'flat', {
    value: function(depth = 1) {
        return this.reduce(function (flat, toFlatten) {
            return flat.concat((Array.isArray(toFlatten) && (depth-1)) ? toFlatten.flat(depth-1) : toFlatten);
        }, []);
    }
});

let flatArr = [1, 2, [3, 4]].flat();

console.log(flatArr); //[1,2,3,4]

 还可以传入参数,有几层嵌套就传入几

 let flatArr2 = [1, 2, [3,  [4, 5] ] ].flat(2);

 console.log(flatArr2) //[1 ,2, 3, 4, 5]

相关文章:

  • 2022-12-23
  • 2021-07-11
  • 2022-12-23
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-28
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案