How can I print out numbers for multiples of 3 that divide without a remainder numbers?
I am attempting to get 3
, 6
, and 9
in array but only 1
prints out, my syntax could be wrong.
var numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; for (var i = 0; i % 3 === 0; i++) { console.log (numbers[i]); }
Two things:
When this i % 3 === 0
check fails your loop stops.
You should check whether the elements( numbers[i]
) of your array are divisible by 3, not the indices( 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]); } }
You should understand more about for loop. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
Code Some think like that:
var numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];
for (var i = 0; i <= 10 ; i++) {
if(numbers[i] % 3 === 0){
console.log (numbers[i]);
}
}
var numbers = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; for (var i = 0; i <= 10; i++){ if( i % 3 === 0 ) { console.log(numbers[i]); } }
var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const res = numbers.forEach((el) => {
if (el % 3 === 0) {
console.log(el);
}
});
just one more way to do it using forEach. LOGIC - If the number is divisible by three then it is a multiple of 3. Try testing to see if when the number is divided by 3 there is a remainder using the modulus operator
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.