简体   繁体   English

Javascript 将 foreach 转换为模循环

[英]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.

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