Array.prototype.flat (数组扁平化) 最近原生的兼容方法
flat()
方法创建一个新的数组,并根据指定深度递归地将所有子数组元素拼接到新的数组中。- 原生方法浏览器兼容性参考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/flat#浏览器兼容性
源码
/**
* [Polyfill] 数组扁平化
* @param {Number} [depth] 扁平深度 (默认值: 1)
* @return {Array}
*/
function arrayFlat(depth = 1) {
let res = [], source = this
for (let i = 0, l = source.length; i < l; i++) {
if (!(i in source)) continue
let item = source[i]
if (depth > 0 && Array.isArray(item)) {
if (depth > 1) item = item.flat(depth - 1)
for (let n = 0, m = item.length; n < m; n++) {
if (n in item) res.push(item[n])
}
} else {
res.push(item)
}
}
return res
}
// Polyfill
Array.prototype.flat || (Array.prototype.flat = arrayFlat)