今天又收获一个生产故障,原因是测试过程中在浏览器里测的,浏览器版本较高,然后这个项目是内嵌在客户端里面,客户端内的浏览器版本稍微低一点,不支持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(); };
标签:isArray,flat,flatMap,target,prop,item,Array,手写 From: https://www.cnblogs.com/maomao93/p/16810137.html