[英]Javascript convert foreach to for loop in modulo
Noob question here.菜鸟问题在这里。 I am trying to convert this forEach to a For loop but for some reason, this is returning undefined:
我正在尝试将此 forEach 转换为 For 循环,但由于某种原因,这将返回未定义:
This is the forEach:这是forEach:
This is the for Loop that keeps displaying undefined:这是一直显示undefined的for循环:
Feel like such a nob for asking this but感觉像问这个问题,但是
Change the condition in your if statement from number%3==0
to number[i]%3==0
.将 if 语句中的条件从
number%3==0
更改为number[i]%3==0
。 Currently, you are checking if the whole list (number) is divisible by 3 or not.目前,您正在检查整个列表(数字)是否可以被 3 整除。 By changing, the condition you check if the particular iteration's index is divisible by 3 or not, also change
i=1
to i=0
, this wail start your loop from the first index.通过更改,您检查特定迭代的索引是否可被 3 整除的条件,还将
i=1
更改为i=0
,这从第一个索引开始循环。
In your if
condition, you are having condition number % 3
instead of number[i] % 3
Correct code:在你的
if
条件下,你有条件number % 3
而不是number[i] % 3
正确的代码:
var number = [1,2,3,4,5,6,7,8,9]; for(var i=0; i<number.length;i++){ if(number[i]%3 == 0){ alert(number[i]); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.