如何在JavaScript的forEach方法中更改索引的步骤? [英] how can i change step of index in forEach method at javascript?

查看:65
本文介绍了如何在JavaScript的forEach方法中更改索引的步骤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是javascript的新手,我不知道如何使用forEach方法更改索引的步骤!

I am new in javascript , I don't know how to change step of index with forEach method!

我需要打印在偶数索引处的元素.我这样做是用for循环的:

for instance I need to print elements which at even indices . I do this with for loop as this :

for (var i=0 ; i<arr.length ; i+=2)
{ 
   console.log(arr[i]);
}

我该如何使用forEach?

how can I do this with forEach?

推荐答案

您不能使用 .forEach()方法跳过索引,但是可以检查当前索引号是否为偶数.如果是,则在该索引处打印数组元素,否则不执行任何操作.

You can't skip indexes with .forEach() method but you can check if the current index number is even or not. If it is, print the array element at that index, otherwise do nothing.

arr.forEach((num, idx) => {
   if (idx % 2 == 0) {
      console.log(num);
   }
});

.forEach()方法与 for 循环相比有所不同.使用 for 循环,您可以控制使用 for 循环遍历数组时用作数组索引的循环变量.

.forEach() method is different as compared to a for loop. Using for loop, you control the loop variable that is used as the array index when iterating over the array using a for loop.

.forEach()方法没有提供该控件,它仅允许您指定 .forEach()方法将使用4个参数调用的回调函数:

.forEach() method doesn't gives you that control, it just allows you to specify a callback function which .forEach() method will call with 4 arguments:

  • 当前数组元素
  • 当前数组元素的索引
  • 在其上调用了 .forEach()方法的整个数组
  • 在回调函数中用作 this 的值
  • Current array element
  • Index of the current array element
  • Whole array over on which .forEach() method was called
  • Value to use as this inside the callback function

使用 .forEach(),您无需担心初始化循环变量,循环终止条件以及循环变量应如何递增.

Using .forEach(), you don't need to worry about initializing the loop variable, loop termination condition and how loop variable should be incremented.

要了解有关 .forEach()方法的更多信息,请参见:

To know more about .forEach() method, see: Array.prototype.forEach()

这篇关于如何在JavaScript的forEach方法中更改索引的步骤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆