手写flat 与 flatMap

今天又收获一个生产故障,原因是测试过程中在浏览器里测的,浏览器版本较高,然后这个项目是内嵌在客户端里面,客户端内的浏览器版本稍微低一点,不支持flat方法和flatMap方法,所以。。。。手写一个呗!

Array.prototype.flat = function (prop = 1) {
  if (typeof (prop) !== 'number') {
    throw new TypeError('prop need Number');
  }
  const that = this;
  if (!Array.isArray(that)) {
    throw new TypeError('Data type is not Array');
  }
  let target = [];
  if (prop === Infinity) {
    target = that;
    do{
      target = target.flat(1);
    }while(target.some(d=>Array.isArray(d)));
    return target
  }
  if (prop <= 0) return that;
  if (that.every(i => !Array.isArray(i))) return that;
  prop--;
  that.forEach(item => {
    if (Array.isArray(item) && item.some(t => Array.isArray(t))) {
      target = target.concat(item.flat(prop));
    } else if (Array.isArray(item)) {
      target = target.concat(item.flat(1))
    } else {
      target.push(item)
    }
  })
  return target
}
Array.prototype.flatMap = function (mapper) {
  return this.map(mapper).flat();
};

  

posted @ 2022-10-20 15:44  疾风_剑豪  阅读(50)  评论(0编辑  收藏  举报