Open qappleh opened 3 years ago
Array.prototype.myFlatMap = function (callback) {
let array = this
const result = []
const getArrayDepth = (arr) => {
if (!Array.isArray(arr)) throw new Error('参数必须是数组')
const map = {
'[': 1,
']': -1
}
let max = 0
let sum = 0
const str = JSON.stringify(arr).split('')
str.forEach(item => {
if (map[item]) {
sum += map[item]
if (sum > max) {
max = sum
}
}
})
return max
}
for (let index = 0; index < array.length; index++) {
const element = array[index]
let target = callback(element)
if (Array.isArray(target)) {
if (getArrayDepth(target) > 1) {
target = target.flat()
result.push(target)
} else {
result.push(...target)
}
} else {
result.push(target)
}
}
return result
}
测试:
[1,2,3,4].myFlatMap(x => [[x * 2]]) // [[2],[4],[6],[8]]
[1,2,3,4].myFlatMap(x => [[x * 2, x * 3]]) // [[2,3],[4,6],[6,9],[8,12]]
[1,2,3,4].myFlatMap(x => [[[x * 2, x * 3]]]) // [[[2,3]],[[4,6]],[[6,9]],[[8,12]]]
提示:Array.prototype.flatMap 已经是 EcmaScript 的标准。