2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
id: ab306dbdcc907c7ddfc30830
|
|
|
|
challengeType: 5
|
2020-09-07 16:10:29 +08:00
|
|
|
forumTopicId: 16079
|
|
|
|
localeTitle: 扁平化
|
2018-10-10 18:03:03 -04:00
|
|
|
---
|
|
|
|
|
|
|
|
## Description
|
2020-09-07 16:10:29 +08:00
|
|
|
<section id='description'>
|
|
|
|
在这道题目中,我们需要写一个数组扁平化的函数。
|
|
|
|
如果你遇到了问题,请点击<a href='https://forum.freecodecamp.one/t/topic/157' target='_blank'>帮助</a>。
|
|
|
|
</section>
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
## Instructions
|
2020-09-07 16:10:29 +08:00
|
|
|
<section id='instructions'>
|
|
|
|
|
2018-10-10 18:03:03 -04:00
|
|
|
</section>
|
|
|
|
|
|
|
|
## Tests
|
|
|
|
<section id='tests'>
|
|
|
|
|
|
|
|
```yml
|
|
|
|
tests:
|
2020-09-07 16:10:29 +08:00
|
|
|
- text: "<code>steamrollArray([[['a']], [['b']]])</code>应该返回<code>['a', 'b']</code>。"
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert.deepEqual(steamrollArray([[["a"]], [["b"]]]), ["a", "b"]);
|
2020-09-07 16:10:29 +08:00
|
|
|
- text: <code>steamrollArray([1, [2], [3, [[4]]]])</code>应该返回<code>[1, 2, 3, 4]</code>。
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert.deepEqual(steamrollArray([1, [2], [3, [[4]]]]), [1, 2, 3, 4]);
|
2020-09-07 16:10:29 +08:00
|
|
|
- text: <code>steamrollArray([1, [], [3, [[4]]]])</code>应该返回<code>[1, 3, 4]</code>。
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert.deepEqual(steamrollArray([1, [], [3, [[4]]]]), [1, 3, 4]);
|
2020-09-07 16:10:29 +08:00
|
|
|
- text: <code>steamrollArray([1, {}, [3, [[4]]]])</code>应该返回<code>[1, {}, 3, 4]</code>。
|
2020-02-18 01:40:55 +09:00
|
|
|
testString: assert.deepEqual(steamrollArray([1, {}, [3, [[4]]]]), [1, {}, 3, 4]);
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Challenge Seed
|
|
|
|
<section id='challengeSeed'>
|
|
|
|
|
|
|
|
<div id='js-seed'>
|
|
|
|
|
|
|
|
```js
|
|
|
|
function steamrollArray(arr) {
|
|
|
|
// I'm a steamroller, baby
|
|
|
|
return arr;
|
|
|
|
}
|
|
|
|
|
|
|
|
steamrollArray([1, [2], [3, [[4]]]]);
|
|
|
|
```
|
|
|
|
|
|
|
|
</div>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
</section>
|
|
|
|
|
|
|
|
## Solution
|
|
|
|
<section id='solution'>
|
|
|
|
|
2020-09-07 16:10:29 +08:00
|
|
|
|
2018-10-10 18:03:03 -04:00
|
|
|
```js
|
2020-09-07 16:10:29 +08:00
|
|
|
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;
|
|
|
|
}
|
2018-10-10 18:03:03 -04:00
|
|
|
```
|
2020-08-13 17:24:35 +02:00
|
|
|
|
2020-09-07 16:10:29 +08:00
|
|
|
</section>
|