0

Okay here goes...I 'm practicing on arrays. I can manage to pick several items from a list using with the for.Each but when it comes to the for loop I am unable to do so. In the for.each I get 3 6 & 9.

var numbers =[1,2,3,4,5,6,7,,8,9,10];
var colors=["blue", "green", "yellow", "red", "white"];
numbers.forEach(function(color){
    if (color%3===0) {
        console.log(color);
    }
});

my for loop code is shown below what am I doing wrong I get the result undefined everytime I ran the code?

var numbers =[1,2,3,4,5,6,7,,8,9,10];
var colors=["blue", "green", "yellow", "red", "white"];
for( i =0; i<numbers.length; i++ ){
    if (numbers%3===0) {
        console.log(numbers[i]);
    }
}
1
  • 1
    numbers%3 -> numbers is an array. This condition will never be true. In order to select individual array items use numbers[i]%3. Commented Jan 4, 2020 at 14:22

1 Answer 1

2

Try this

var numbers =[1,2,3,4,5,6,7,,8,9,10];
var colors=["blue", "green", "yellow", "red", "white"];
for( i =0; i<numbers.length; i++ ){
  if (numbers[i]%3===0) {
    console.log(numbers[i]);
  }
}

While iterating over for loop in an array you forgot to add numbers[i]

Sign up to request clarification or add additional context in comments.

4 Comments

why am are we adding [i] in ( if (numbers[i]%3===0)) after numbers while in the for.each we did not add it? Still new to Js
In for loop you are accessing each element by specifying numbers[i] where i =0,1,2 and so on till numbers.length.
please read more about the loops you will get a better understanding.
you're welcome. please accept my answer by ticking it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.