Files

1.4 KiB
Raw Permalink Blame History

id, title, challengeType, videoUrl, forumTopicId, dashedName
id title challengeType videoUrl forumTopicId dashedName
56105e7b514f539506016a5e 使用 For 循環反向遍歷數組 1 https://scrimba.com/c/c2R6BHa 16808 count-backwards-with-a-for-loop

--description--

只要我們定義好合適的條件for 循環也可以反向遍歷。

爲了讓每次遞減 2我們需要改變 initialization、condition 和 final-expression。

設置 i = 10,並且當 i > 0 的時候才繼續循環。 我們使用 i -= 2 來讓 i 每次循環遞減 2。

const ourArray = [];

for (let i = 10; i > 0; i -= 2) {
  ourArray.push(i);
}

ourArray 現在將包含 [10, 8, 6, 4, 2]。 讓我們改變初始值和最後的表達式,這樣我們就可以按照奇數從後往前兩兩倒着數。

--instructions--

使用一個 for循環,把從 9 到 1 的奇數添加到 myArray

--hints--

應該使用 for 循環。

assert(/for\s*\([^)]+?\)/.test(code));

應該使用數組方法 push

assert(code.match(/myArray.push/));

myArray 應該等於 [9, 7, 5, 3, 1]

assert.deepEqual(myArray, [9, 7, 5, 3, 1]);

--seed--

--after-user-code--

if(typeof myArray !== "undefined"){(function(){return myArray;})();}

--seed-contents--

// Setup
const myArray = [];

// Only change code below this line

--solutions--

const myArray = [];
for (let i = 9; i > 0; i -= 2) {
  myArray.push(i);
}