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

【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(depth1){letsourcethis,res[]for(leti0,lsource.length;il;i){if(!(iinsource))continueletitemsource[i]if(depth0Array.isArray(item)){if(depth1)itemarrayFlat.call(item,depth-1)for(letn0,mitem.length;nm;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.flatarrayFlat)Array.prototype.flatMap||(Array.prototype.flatMaparrayFlatMap)