2018-09-30 23:01:58 +01:00
|
|
|
---
|
|
|
|
id: 56104e9e514f539506016a5c
|
|
|
|
title: Iterate Odd Numbers With a For Loop
|
|
|
|
challengeType: 1
|
2019-02-14 12:24:02 -05:00
|
|
|
videoUrl: 'https://scrimba.com/c/cm8n7T9'
|
2019-07-31 11:32:23 -07:00
|
|
|
forumTopicId: 18212
|
2018-09-30 23:01:58 +01:00
|
|
|
---
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
# --description--
|
|
|
|
|
|
|
|
For loops don't have to iterate one at a time. By changing our `final-expression`, we can count by even numbers.
|
|
|
|
|
|
|
|
We'll start at `i = 0` and loop while `i < 10`. We'll increment `i` by 2 each loop with `i += 2`.
|
2019-05-17 06:20:30 -07:00
|
|
|
|
|
|
|
```js
|
|
|
|
var ourArray = [];
|
|
|
|
for (var i = 0; i < 10; i += 2) {
|
|
|
|
ourArray.push(i);
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
`ourArray` will now contain `[0,2,4,6,8]`. Let's change our `initialization` so we can count by odd numbers.
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
# --instructions--
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
Push the odd numbers from 1 through 9 to `myArray` using a `for` loop.
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
# --hints--
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
You should be using a `for` loop for this.
|
2018-09-30 23:01:58 +01:00
|
|
|
|
|
|
|
```js
|
2020-11-27 19:02:05 +01:00
|
|
|
assert(/for\s*\([^)]+?\)/.test(code));
|
|
|
|
```
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
`myArray` should equal `[1,3,5,7,9]`.
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
```js
|
|
|
|
assert.deepEqual(myArray, [1, 3, 5, 7, 9]);
|
2018-09-30 23:01:58 +01:00
|
|
|
```
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
# --seed--
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
## --after-user-code--
|
2018-09-30 23:01:58 +01:00
|
|
|
|
|
|
|
```js
|
2018-10-20 21:02:47 +03:00
|
|
|
if(typeof myArray !== "undefined"){(function(){return myArray;})();}
|
2018-09-30 23:01:58 +01:00
|
|
|
```
|
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
## --seed-contents--
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
```js
|
|
|
|
// Setup
|
|
|
|
var myArray = [];
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
// Only change code below this line
|
|
|
|
```
|
2018-09-30 23:01:58 +01:00
|
|
|
|
2020-11-27 19:02:05 +01:00
|
|
|
# --solutions--
|
2018-09-30 23:01:58 +01:00
|
|
|
|
|
|
|
```js
|
|
|
|
var myArray = [];
|
|
|
|
for (var i = 1; i < 10; i += 2) {
|
|
|
|
myArray.push(i);
|
|
|
|
}
|
|
|
|
```
|