1.4 KiB
1.4 KiB
id, title, challengeType, videoUrl, forumTopicId
id | title | challengeType | videoUrl | forumTopicId |
---|---|---|---|---|
5675e877dbd60be8ad28edc6 | 使用 For 循环遍历数组 | 1 | https://scrimba.com/c/caeR3HB | 18216 |
--description--
迭代输出一个数组的每个元素是 JavaScript 中的常见需求,for
循环可以做到这一点。下面的代码将输出数组 arr
的每个元素到控制台:
var arr = [10, 9, 8, 7, 6];
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
记住数组的索引从零开始的,这意味着数组的最后一个元素的下标是:数组的长度 -1。我们这个循环的 条件是i < arr.length
,当i
的值为 长度 -1 的时候循环就停止了。在这个例子中,最后一个循环是 i === 4,也就是说,当i的值等于arr.length时,结果输出 6。
--instructions--
声明并初始化一个变量total
为0
。使用for
循环,使得total
的值为myArr
的数组中的每个元素的值的总和。
--hints--
total
应该被声明, 并且初始化值为 0。
assert(code.match(/var.*?total\s*=\s*0.*?;/));
total
应该等于 20。
assert(total === 20);
你应该使用for
循环在myArr
中遍历。
assert(code.match(/for\s*\(/g).length > 1 && code.match(/myArr\s*\[/));
不能直接把total
设置成 20。
assert(!code.match(/total[\s\+\-]*=\s*(\d(?!\s*[;,])|[1-9])/g));