简体   繁体   中英

Returning numbers divisible by 3 within an array using a For Loop?

I am trying to return numbers to the console that are divisible by 3 within the array below, using a for loop as seen below.

It is returning numbers 2-9 into the console, but not the ones divisible by 3? I am stumped? What am I doing wrong?

var numbers = [1,2,3,4,5,6,7,8,9,10]

for(var i = 0; i < numbers.length; i++) {
    if(i % 3){
       console.log(numbers[i]);
    }
}

The if statement branches based on the result of the conditional statement. if(i % 3){ will return true anytime the result of the modulo operation is not 0 because any non-zero number converts to true .

The statement should be: if(i % 3 === 0){ because you only want to branch into the true section if you divide by 3 and the remainder is 0 .

Next, you are using your loop index as the number to operate on, but you need to use the array item with the index of your loop counter numbers[i] , not i .

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

Also, a simpler approach here may be to use Array.filter() , which loops over the array and returns a new array with the values you specify:

 var numbers = [1,2,3,4,5,6,7,8,9,10]; var results = numbers.filter(function(num){ return num % 3 === 0; }); console.log(results); 

 var numbers = [1,2,3,4,5,6,7,8,9,10]; numbers.forEach(n => { if (n % 3 === 0) console.log(n); }); 

The problem is your if statement. Please see the example.

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

One thing that you are doing wrong is that you are using i instead of numbers[i] and secondly you are not comparing it to 0 . It should be something like:

var numbers = [1,2,3,4,5,6,7,8,9,10]

for(var i = 0; i < numbers.length; i++) {
    if(numbers[i] % 3==0){
    console.log(numbers[i]);}}

ES6

You can also achieve by using Unary Negation Operator (Exclamation Mark) with help of reduce()

DEMO

 var numbers = [1,2,3,4,5,6,7,8,9,10] console.log(numbers.reduce((r,v)=>!(v%3)?r.concat(v):r,[])) 
 .as-console-wrapper {max-height: 100% !important;top: 0;} 

With help of filter()

DEMO

 var numbers = [1,2,3,4,5,6,7,8,9,10] console.log(numbers.filter(v=>!(v%3))) 
 .as-console-wrapper {max-height: 100% !important;top: 0;} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM