2.0 KiB
2.0 KiB
id, challengeType, videoUrl, forumTopicId, localeTitle
id | challengeType | videoUrl | forumTopicId | localeTitle |
---|---|---|---|---|
56105e7b514f539506016a5e | 1 | https://scrimba.com/c/c2R6BHa | 16808 | 使用 For 循环反向遍历数组 |
Description
初始化
,条件判断
和计数器
。
我们让i = 10
,并且当i > 0
的时候才继续循环。我们使用i -= 2
来让i
每次循环递减 2。
var ourArray = [];
for (var i=10; i > 0; i-=2) {
ourArray.push(i);
}
循环结束后,ourArray
的值为[10,8,6,4,2]
。
让我们改变初始化
和计数器
,这样我们就可以按照奇数从后往前两两倒着数。
Instructions
for
循环,把 9 到 1 的奇数添加进myArray
。
Tests
tests:
- text: 你应该使用<code>for</code>循环。
testString: assert(code.match(/for\s*\(/g).length > 1);
- text: 你应该使用数组方法<code>push</code>。
testString: assert(code.match(/myArray.push/));
- text: <code>myArray</code>应该等于<code>[9,7,5,3,1]</code>。
testString: assert.deepEqual(myArray, [9,7,5,3,1]);
Challenge Seed
// Example
var ourArray = [];
for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}
// Setup
var myArray = [];
// Only change code below this line.
After Test
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
Solution
var ourArray = [];
for (var i = 10; i > 0; i -= 2) {
ourArray.push(i);
}
var myArray = [];
for (var i = 9; i > 0; i -= 2) {
myArray.push(i);
}