* feat(tools): add seed/solution restore script * chore(curriculum): remove empty sections' markers * chore(curriculum): add seed + solution to Chinese * chore: remove old formatter * fix: update getChallenges parse translated challenges separately, without reference to the source * chore(curriculum): add dashedName to English * chore(curriculum): add dashedName to Chinese * refactor: remove unused challenge property 'name' * fix: relax dashedName requirement * fix: stray tag Remove stray `pre` tag from challenge file. Signed-off-by: nhcarrigan <nhcarrigan@gmail.com> Co-authored-by: nhcarrigan <nhcarrigan@gmail.com>
2.5 KiB
2.5 KiB
id, title, challengeType, videoUrl, forumTopicId, dashedName
id | title | challengeType | videoUrl | forumTopicId | dashedName |
---|---|---|---|---|---|
5a2efd662fb457916e1fe604 | do...while 循环 | 1 | https://scrimba.com/c/cDqWGcp | 301172 | iterate-with-javascript-do---while-loops |
--description--
这一节我们将要学习的是do...while
循环,它会先执行do
里面的代码,如果while
表达式为真则重复执行,反之则停止执行。我们来看一个例子。
var ourArray = [];
var i = 0;
do {
ourArray.push(i);
i++;
} while (i < 5);
这看起来和其他循环语句差不多,返回的结果是[0, 1, 2, 3, 4]
,do...while
与其他循环不同点在于,初始条件为假时的表现,让我们通过实际的例子来看看。 这是一个普通的 while 循环,只要i < 5
,它就会在循环中运行代码。
var ourArray = [];
var i = 5;
while (i < 5) {
ourArray.push(i);
i++;
}
注意,我们首先将i
的值初始化为 5。执行下一行时,注意到i
不小于 5,循环内的代码将不会执行。所以ourArray
最终没有添加任何内容,因此示例中的所有代码执行完时,ourArray
仍然是[]
。 现在,看一下do...while
循环。
var ourArray = [];
var i = 5;
do {
ourArray.push(i);
i++;
} while (i < 5);
在这里,和使用 while 循环时一样,我们将i
的值初始化为 5。执行下一行时,没有检查i
的值,直接执行花括号内的代码。数组会添加一个元素,并在进行条件检查之前递增i
。然后,在条件检查时因为i
等于 6 不符合条件i < 5
,所以退出循环。最终ourArray
的值是[5]
。 本质上,do...while
循环确保循环内的代码至少运行一次。 让我们通过do...while
循环将值添加到数组中。
--instructions--
将代码中的while
循环更改为do...while
循环,实现数字 10 添加到myArray
中,代码执行完时,i
等于11
。
--hints--
你应该使用do...while
循环。
assert(code.match(/do/g));
myArray
应该等于[10]
。
assert.deepEqual(myArray, [10]);
i
应该等于11
。
assert.deepEqual(i, 11);
--seed--
--after-user-code--
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
--seed-contents--
// Setup
var myArray = [];
var i = 10;
// Only change code below this line
while (i < 5) {
myArray.push(i);
i++;
}
--solutions--
var myArray = [];
var i = 10;
do {
myArray.push(i);
i++;
} while (i < 5)