[英]How print out numbers for multiples of 3 that divide without a remainder numbers?
How can I print out numbers for multiples of 3 that divide without a remainder numbers?如何打印出 3 的倍数除以没有余数的数字?
I am attempting to get 3
, 6
, and 9
in array but only 1
prints out, my syntax could be wrong.我试图在数组中获取3
、 6
和9
但只有1
打印出来,我的语法可能是错误的。
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.当此i % 3 === 0
检查失败时,您的循环将停止。
You should check whether the elements( numbers[i]
) of your array are divisible by 3, not the indices( i
).您应该检查数组的元素( numbers[i]
)是否可以被 3 整除,而不是索引( 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.您应该更多地了解 for 循环。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for 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.只是使用 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逻辑 - 如果数字可以被 3 整除,则它是 3 的倍数。尝试使用模运算符测试当数字除以 3 时是否有余数
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.