【JS Polyfill】Array.prototype.flat  flatMap (数组扁平化) 最近原生的兼容方法

Array.prototype.flat & flatMap (数组扁平化)

  • flat方法创建一个新的数组,并根据指定深度递归地将所有子数组元素拼接到新的数组中。
  • flatMap方法对数组中的每个元素应用给定的回调函数,然后将结果展开一级,返回一个新数组。
  • 原生方法浏览器兼容性参考:https://caniuse.com/array-flat

兼容方案源码

/** * [Polyfill] 数组扁平化 * @param {Number} [depth] 扁平深度 (默认值: 1) * @return {Array} */functionarrayFlat(depth=1){letsource=this,res=[]for(leti=0,l=source.length;i<l;i++){if(!(iinsource))continueletitem=source[i]if(depth>0&&Array.isArray(item)){if(depth>1)item=arrayFlat.call(item,depth-1)for(letn=0,m=item.length;n<m;n++){if(ninitem)res.push(item[n])}}else{res.push(item)}}returnres}/** * [Polyfill] 数组遍历写入并扁平化 * @param {Function} callbackFn 遍历函数。暴露参数: (item: 当前处理元素, index: 当前元素索引, array: 当前调用的数组) * @param {*} thisArg 遍历函数的作用域 * @return {Array} */functionarrayFlatMap(){returnarrayFlat.call(Array.prototype.map.apply(this,arguments),1)}// PolyfillArray.prototype.flat||(Array.prototype.flat=arrayFlat)Array.prototype.flatMap||(Array.prototype.flatMap=arrayFlatMap)