2018-10-10 18:03:03 -04:00
|
|
|
|
---
|
|
|
|
|
id: 56105e7b514f539506016a5e
|
2020-12-16 00:37:30 -07: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/c2R6BHa'
|
|
|
|
|
forumTopicId: 16808
|
2021-01-13 03:31:00 +01:00
|
|
|
|
dashedName: count-backwards-with-a-for-loop
|
2018-10-10 18:03:03 -04:00
|
|
|
|
---
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --description--
|
|
|
|
|
|
2020-04-29 18:29:13 +08:00
|
|
|
|
for循环也可以逆向迭代,只要我们定义好合适的条件。
|
2020-12-16 00:37:30 -07:00
|
|
|
|
|
|
|
|
|
为了让每次倒数递减 2,我们需要改变我们的`初始化`,`条件判断`和`计数器`。
|
|
|
|
|
|
|
|
|
|
我们让`i = 10`,并且当`i > 0`的时候才继续循环。我们使用`i -= 2`来让`i`每次循环递减 2。
|
2020-04-29 18:29:13 +08:00
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
var ourArray = [];
|
|
|
|
|
for (var i=10; i > 0; i-=2) {
|
|
|
|
|
ourArray.push(i);
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
循环结束后,`ourArray`的值为`[10,8,6,4,2]`。 让我们改变`初始化`和`计数器`,这样我们就可以按照奇数从后往前两两倒着数。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --instructions--
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
使用一个`for`循环,把 9 到 1 的奇数添加进`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
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
你应该使用`for`循环。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
|
assert(code.match(/for\s*\(/g).length > 1);
|
2018-10-10 18:03:03 -04:00
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
你应该使用数组方法`push`。
|
2018-10-10 18:03:03 -04:00
|
|
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
|
assert(code.match(/myArray.push/));
|
2018-10-10 18:03:03 -04:00
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
`myArray`应该等于`[9,7,5,3,1]`。
|
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, [9, 7, 5, 3, 1]);
|
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
|
|
|
|
|
var myArray = [];
|
|
|
|
|
|
|
|
|
|
// Only change code below this line
|
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
|
# --solutions--
|
|
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
|
```js
|
|
|
|
|
var myArray = [];
|
|
|
|
|
for (var i = 9; i > 0; i -= 2) {
|
|
|
|
|
myArray.push(i);
|
|
|
|
|
}
|
|
|
|
|
```
|