-
Notifications
You must be signed in to change notification settings - Fork 0
/
数组拍平2.html
33 lines (30 loc) · 957 Bytes
/
数组拍平2.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>数组拍平(二)</title>
</head>
<body>
<h3>编写一个 JavaScript generator 函数,接受一个仅包含数字的 多维数组 ,返回一个迭代器,可以遍历得到它拍平以后的结果。例如:</h3>
<pre>
const numbers = flatten2([1, [[2], 3, 4], 5])
numbers.next().value // => 1
numbers.next().value // => 2
numbers.next().value // => 3
numbers.next().value // => 4
numbers.next().value // => 5
</pre>
<script>
function* flatten2(arr) {
if (!arr || arr.length === 0) return '';
const arr2 = arr.toString().split(',').map(Number)
for (let i = 0; i < arr2.length; i++) {
yield arr2[i]
}
}
const numbers = flatten2([1, [[2], 3, 4], 5])
</script>
</body>
</html>