2018-10-10 22:03:03 +00:00
|
|
|
---
|
|
|
|
id: ab306dbdcc907c7ddfc30830
|
2021-03-15 03:20:39 +00:00
|
|
|
title: 数组扁平化
|
2018-10-10 22:03:03 +00:00
|
|
|
challengeType: 5
|
2020-09-07 08:10:29 +00:00
|
|
|
forumTopicId: 16079
|
2021-01-13 02:31:00 +00:00
|
|
|
dashedName: steamroller
|
2018-10-10 22:03:03 +00:00
|
|
|
---
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --description--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
嵌套数组扁平化成一维数组。 必须考虑到各种深度的嵌套层级。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --hints--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
`steamrollArray([[["a"]], [["b"]]])` 应返回 `["a", "b"]`。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
```js
|
|
|
|
assert.deepEqual(steamrollArray([[['a']], [['b']]]), ['a', 'b']);
|
2018-10-10 22:03:03 +00:00
|
|
|
```
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
`steamrollArray([1, [2], [3, [[4]]]])` 应返回 `[1, 2, 3, 4]`。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
assert.deepEqual(steamrollArray([1, [2], [3, [[4]]]]), [1, 2, 3, 4]);
|
2018-10-10 22:03:03 +00:00
|
|
|
```
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
`steamrollArray([1, [], [3, [[4]]]])` 应返回 `[1, 3, 4]`。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
```js
|
|
|
|
assert.deepEqual(steamrollArray([1, [], [3, [[4]]]]), [1, 3, 4]);
|
|
|
|
```
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
`steamrollArray([1, {}, [3, [[4]]]])` 应返回 `[1, {}, 3, 4]`。
|
2020-09-07 08:10:29 +00:00
|
|
|
|
2018-10-10 22:03:03 +00:00
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
assert.deepEqual(steamrollArray([1, {}, [3, [[4]]]]), [1, {}, 3, 4]);
|
2018-10-10 22:03:03 +00:00
|
|
|
```
|
2020-08-13 15:24:35 +00:00
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
代码中不应使用 `Array.prototype.flat()` 或 `Array.prototype.flatMap()` 方法。
|
2021-01-12 16:18:51 +00:00
|
|
|
|
|
|
|
```js
|
|
|
|
assert(!code.match(/\.\s*flat\s*\(/) && !code.match(/\.\s*flatMap\s*\(/));
|
|
|
|
```
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
# --seed--
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
```js
|
|
|
|
function steamrollArray(arr) {
|
|
|
|
return arr;
|
|
|
|
}
|
|
|
|
|
|
|
|
steamrollArray([1, [2], [3, [[4]]]]);
|
|
|
|
```
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --solutions--
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
```js
|
|
|
|
function steamrollArray(arr) {
|
|
|
|
if (!Array.isArray(arr)) {
|
|
|
|
return [arr];
|
|
|
|
}
|
|
|
|
var out = [];
|
|
|
|
arr.forEach(function(e) {
|
|
|
|
steamrollArray(e).forEach(function(v) {
|
|
|
|
out.push(v);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
return out;
|
|
|
|
}
|
|
|
|
```
|