-
Notifications
You must be signed in to change notification settings - Fork 0
/
数组拍平.html
48 lines (45 loc) · 1.4 KB
/
数组拍平.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!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 函数,接受一个仅包含数字的 多维数组 ,返回拍平以后的结果。</h3>
<p>例如传入:[1, [[2], 3, 4], 5],返回 [1, 2, 3, 4, 5]。</p>
<script>
const data = [1, [[2], 3, 4], 5];
// 解法一
const flatten = (arr) => {
return arr.length ? arr.toString().split(',').map(Number) : []
}
// 解法二
const flatten2 = (arr) => {
let result = []
arr.forEach(el => {
if (typeof (el) === 'number') {
result.push(el);
} else {
const item = flatten2.call(null, el);
result = result.concat(item)
}
})
return result;
}
// 解法三
const flatten3 = (arr) => {
if (arr.length === 0) return [];
const reg = /\[|\]/g;
let str = JSON.stringify(arr);
str = str.replace(reg, '')
str = str.split(',').map(Number)
return str;
}
console.log(flatten(data))
console.log(flatten2(data))
console.log(flatten3(data))
</script>
</body>
</html>