Created
November 14, 2017 06:48
-
-
Save Shuumatsu/bf2f1cd446c52609fa39b32d705f5028 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// 常规的递归方法 | |
const flatten1 = arr => { | |
const result = [] | |
for (const v of arr) { | |
Array.isArray(v) ? | |
result.push(...flatten(v)) : | |
result.push(v) | |
} | |
return result | |
} | |
// GeneratorFunction 版的递归,配合 take 还可以达到仅打平到前多少位的效果 | |
const flatten2 = function* (arr) { | |
for (const v of arr) { | |
if (Array.isArray(v)) { | |
yield* flatten(v) | |
continue | |
} | |
yield v | |
} | |
} | |
// 幽灵打平法,假设数字元素均为数字 | |
const flatten3 = arr => arr.toString().split(',') | |
const flatten4 = arr => JSON.parse(`[${arr}]`) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment