数组迭代:将forEach循环重写为for循环

时间:2020-07-25 17:06:48

标签: javascript arrays

对于练习,我必须将此forEach循环重写为for循环:

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

numbers.forEach(function(number){
  if(number % 3 === 0) {
   console.log(number);
  }
});

我想出了以下内容,但是由于它给了我未定义的含义,因此并没有真正起作用:

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

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

有人可以向我解释哪里出了问题吗?

4 个答案:

答案 0 :(得分:2)

if(numbers[i] % 3 === 0) {
     console.log(numbers[i]);
 } 

答案 1 :(得分:2)

您需要使用i-th的{​​{1}}(当前一个)元素:

numbers

答案 2 :(得分:2)

您必须使用数字的第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]);
        } 
    };

答案 3 :(得分:1)

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

function fun(number) {
  if (number % 3 === 0) {
    console.log(number);
  }
}

// Your code with `forEach` 
numbers.forEach(fun);

// Same with for-loop when convert
for (var i = 0; i < numbers.length; i++) {
  fun(numbers[i]);
}

// you are using `numbers % 3`, numbers is an array and you actually you wanted to use with number (which will be `numbers[i]`