2018-10-10 18:03:03 -04:00
|
|
|
|
---
|
|
|
|
|
id: 56104e9e514f539506016a5c
|
2021-03-14 21:20:39 -06:00
|
|
|
|
title: 使用 For 循环遍历数组的奇数
|
2018-10-10 18:03:03 -04:00
|
|
|
|
challengeType: 1
|
2020-04-29 18:29:13 +08:00
|
|
|
|
videoUrl: 'https://scrimba.com/c/cm8n7T9'
|
|
|
|
|
forumTopicId: 18212
|
2021-01-13 03:31:00 +01:00
|
|
|
|
dashedName: iterate-odd-numbers-with-a-for-loop
|
2018-10-10 18:03:03 -04:00
|
|
|
|
---
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --description--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
2021-03-14 21:20:39 -06:00
|
|
|
|
对于循环,一次不必递增一个。 通过更改我们的 `final-expression`,我们可以用偶数来计数。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
2021-03-14 21:20:39 -06:00
|
|
|
|
初始化 `i = 0`,当 `i < 10` 的时候继续循环。 `i += 2` 让 `i` 每次循环之后增加 2。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
|
|
```js
|
2021-11-06 08:56:52 -07:00
|
|
|
|
const ourArray = [];
|
|
|
|
|
|
|
|
|
|
for (let i = 0; i < 10; i += 2) {
|
2018-10-10 18:03:03 -04:00
|
|
|
|
ourArray.push(i);
|
|
|
|
|
}
|
2020-12-16 00:37:30 -07:00
|
|
|
|
```
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
2021-11-06 08:56:52 -07:00
|
|
|
|
`ourArray` 现在将包含 `[0, 2, 4, 6, 8]`。 改变计数器(`initialization`) ,这样我们可以用奇数来递增。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --instructions--
|
2020-04-29 18:29:13 +08:00
|
|
|
|
|
2021-03-14 21:20:39 -06:00
|
|
|
|
写一个 `for` 循环,把从 1 到 9 的奇数添加到 `myArray`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --hints--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
2021-03-14 21:20:39 -06:00
|
|
|
|
应该使用 `for` 循环。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
|
|
```js
|
2021-02-06 04:42:36 +00:00
|
|
|
|
assert(/for\s*\([^)]+?\)/.test(code));
|
2018-10-10 18:03:03 -04:00
|
|
|
|
```
|
|
|
|
|
|
2021-11-06 08:56:52 -07:00
|
|
|
|
`myArray` 应该等于 `[1, 3, 5, 7, 9]`。
|
2020-04-29 18:29:13 +08:00
|
|
|
|
|
2018-10-10 18:03:03 -04:00
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
|
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);
|
2018-10-10 18:03:03 -04:00
|
|
|
|
```
|
2020-04-29 18:29:13 +08:00
|
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
|
# --seed--
|
|
|
|
|
|
|
|
|
|
## --after-user-code--
|
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
// Setup
|
2021-11-06 08:56:52 -07:00
|
|
|
|
const myArray = [];
|
2021-01-13 03:31:00 +01:00
|
|
|
|
|
|
|
|
|
// Only change code below this line
|
2021-11-06 08:56:52 -07:00
|
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --solutions--
|
|
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
|
```js
|
2021-11-06 08:56:52 -07:00
|
|
|
|
const myArray = [];
|
|
|
|
|
for (let i = 1; i < 10; i += 2) {
|
2021-01-13 03:31:00 +01:00
|
|
|
|
myArray.push(i);
|
|
|
|
|
}
|
|
|
|
|
```
|