您现在的位置是:网站首页> 编程资料编程资料

Javascript数组的 forEach 方法详细介绍_javascript技巧_

2023-05-24 253人已围观

简介 Javascript数组的 forEach 方法详细介绍_javascript技巧_

前言

在JavaScript 中数组的遍历 有很多中方法, 其中有一种 使用 foreach 来遍历数组。

mdn官方文档

语法:

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

参数:

  • callback

为数组中每个元素执行的函数,该函数接收一至三个参数:currentValue数组中正在处理的当前元素。index 可选数组中正在处理的当前元素的索引。array 可选forEach() 方法正在操作的数组。

  • thisArg 可选

可选参数。当执行回调函数 callback 时,用作 this 的值。

在forEach 中传入一个 callback 函数, 函数最多可以接收 三个值, 分别为当前正在遍历的值, 当前值对应的索引,以及当前数组本身

小试

现在有一个场景,我和我的室友们,现在在一个数组里面。 按照排行分别为: 老大,老二,老三, … ,老六, 小七.

var arr = ['Liu laoda', 'Li laoer', 'Wei laosan', 'Frank', 'Guan laowu', 'Yang laoliu', 'Li xiaoqi']; // 在 forEach 中 传入 一个function ,接收两个参数 arr.forEach(function(name,index){ console.log(name, ' - ',index); })

结果如下: 第一个参数就是 当前遍历的元素,第二参数为当前元素的索引

注意:forEach() 为每个数组元素执行一次 callback 函数 ,即每个元素都会执行一次callback 函数

来看看回调函数的第三个参数 ,表示 就是这个数组本身。

var arr = ['Liu laoda', 'Li laoer', 'Wei laosan']; arr.forEach(function(name,index,person){ console.log(name, ' - ',index); console.log(person); })

还有一个参数 thisArg 这个参数

当回调函数执行的时候, 回调函数中 使用this 就是这个值。来看一个例子

var arr = ['Liu laoda', 'Li laoer', 'Wei laosan']; // thisArg 此时传入 {'name':'frank'},当回调函数执行的时候,this 就是这个值。 arr.forEach(function(name,index){ console.log(this); },{'name':'frank'})

如果省略了 thisArg 参数,或者其值为 nullundefinedthis 则指向全局对象。

var arr = ['Liu laoda', 'Li laoer', 'Wei laosan']; // 没有传thisArg 参数 arr.forEach(function(name,index){ // 此时是window console.log(this); })

使用forEach注意事项

除了抛出异常以外,没有办法中止或跳出 forEach() 循环。如果你需要中止或跳出循环,forEach() 方法不是应当使用的工具。

forEach 不支持 break这种语句退出循环。

如果你想在遍历数组的过程中想要 提前终止循环,就不要使用 forEach 遍历, 可以使用for 循环来遍历数组.

例如:我只想遍历到i==0 的时候,提前终止循环

var arr = ['Liu laoda', 'Li laoer', 'Wei laosan']; for (let i = 0; i < arr.length; i++) { if (i === 1) { break; } console.log(arr[i],'-', i); } // Liu laoda - 0

到此这篇关于Javascript数组的 forEach 方法详细介绍的文章就介绍到这了,更多相关JS  forEach内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

-六神源码网