Created
September 12, 2020 12:14
-
-
Save lilywang711/733d7fac5a86224d6a4c55d2cc935b70 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Array.prototype.customReduce = function (fn, initialValue) { | |
for (let i = 0; i < this.length; i++) { | |
// 当未传初始值时取数组中的第一项作为初始值 | |
if (typeof initialValue === "undefined") { | |
initialValue = fn(this[i], this[i + 1], i, this); | |
i++; | |
} else { | |
initialValue = fn(initialValue, this[i], i, this); | |
} | |
} | |
return initialValue; | |
}; | |
let arr = [ | |
1, | |
[1, 2, 2], | |
[3, 4, 5, 5], | |
[6, 7, 8, 9, [11, 12, [12, 13, [14]]]], | |
10 | |
]; | |
const flatten2 = (arr) => | |
arr.customReduce((acc, cur, index, array) => { | |
if (Array.isArray(cur)) { | |
return acc.concat(flatten2(cur)); | |
} else { | |
return acc.concat(cur); | |
} | |
}, []); | |
console.log(flatten2(arr)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment