2018-10-10 22:03:03 +00:00
|
|
|
|
---
|
|
|
|
|
id: cf1111c1c11feddfaeb1bdef
|
2021-03-15 03:20:39 +00:00
|
|
|
|
title: while 循环
|
2018-10-10 22:03:03 +00:00
|
|
|
|
challengeType: 1
|
2020-04-29 10:29:13 +00:00
|
|
|
|
videoUrl: 'https://scrimba.com/c/c8QbnCM'
|
|
|
|
|
forumTopicId: 18220
|
2021-01-13 02:31:00 +00:00
|
|
|
|
dashedName: iterate-with-javascript-while-loops
|
2018-10-10 22:03:03 +00:00
|
|
|
|
---
|
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --description--
|
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
你可以使用循环多次执行相同的代码。
|
2020-12-16 07:37:30 +00:00
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
我们将学习的第一种类型的循环称为 `while` 循环,当 while 指定的条件为真,循环才会执行,反之不执行。
|
2020-04-29 10:29:13 +00:00
|
|
|
|
|
|
|
|
|
```js
|
2021-11-06 15:56:52 +00:00
|
|
|
|
const ourArray = [];
|
|
|
|
|
let i = 0;
|
|
|
|
|
|
|
|
|
|
while (i < 5) {
|
2020-04-29 10:29:13 +00:00
|
|
|
|
ourArray.push(i);
|
|
|
|
|
i++;
|
|
|
|
|
}
|
|
|
|
|
```
|
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
在上面的代码里,`while` 循环执行 5 次把 0 到 4 的数字添加到 `ourArray` 数组里。
|
2020-04-29 10:29:13 +00:00
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
让我们通过 while 循环将值添加到数组中。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --instructions--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
2021-03-15 03:20:39 +00:00
|
|
|
|
通过一个 `while` 循环,把从 5 到 0(包括 5 和 0) 的值添加到 `myArray` 中。
|
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
|
|
|
|
你应该使用 `while` 循环。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
|
assert(code.match(/while/g));
|
2018-10-10 22:03:03 +00:00
|
|
|
|
```
|
|
|
|
|
|
2021-11-06 15:56:52 +00:00
|
|
|
|
`myArray` 应该等于 `[5, 4, 3, 2, 1, 0]`。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
|
|
|
|
```js
|
2021-02-06 04:42:36 +00:00
|
|
|
|
assert.deepEqual(myArray, [5, 4, 3, 2, 1, 0]);
|
2018-10-10 22:03:03 +00:00
|
|
|
|
```
|
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
|
# --seed--
|
|
|
|
|
|
|
|
|
|
## --after-user-code--
|
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
|
|
|
|
```
|
|
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
|
|
```js
|
|
|
|
|
// Setup
|
2021-11-06 15:56:52 +00:00
|
|
|
|
const myArray = [];
|
2021-01-13 02:31:00 +00:00
|
|
|
|
|
|
|
|
|
// Only change code below this line
|
2021-11-06 15:56:52 +00:00
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
|
```
|
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
|
# --solutions--
|
2020-04-29 10:29:13 +00:00
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
|
```js
|
2021-11-06 15:56:52 +00:00
|
|
|
|
const myArray = [];
|
|
|
|
|
let i = 5;
|
|
|
|
|
while (i >= 0) {
|
2021-01-13 02:31:00 +00:00
|
|
|
|
myArray.push(i);
|
|
|
|
|
i--;
|
|
|
|
|
}
|
|
|
|
|
```
|