JavaScript中的forEach()是一个非常有用的循环遍历方法,它可以用来遍历数组中的元素。使用forEach()遍历数组的方法如下:
定义一个数组,比如:let arr = [1, 2, 3, 4, 5];
使用forEach()方法来遍历数组,比如:arr.forEach(function(element, index, array){ //code});
其中,element表示当前元素,index表示当前元素的索引,array表示当前数组。
比如,在上面的例子中,我们可以使用forEach()循环遍历数组,并打印出每个元素:
arr.forEach(function(element, index, array){
console.log("Element: "+element+", Index: "+index);
});
运行结果如下:
Element: 1, Index: 0
Element: 2, Index: 1
Element: 3, Index: 2
Element: 4, Index: 3
Element: 5, Index: 4
可以看到,forEach()循环遍历数组的方法非常简单,只需要定义一个数组,使用forEach()方法来遍历数组即可。
forEach()还支持传入一个回调函数,比如:arr.forEach(function(element, index, array){ //code}, thisArg),其中thisArg表示回调函数的上下文。
例如,我们可以传入一个thisArg,并在回调函数中使用thisArg:
let obj = {name: "John"};
arr.forEach(function(element, index, array){
console.log(this.name);
}, obj);
运行结果如下:
John
John
John
John
John
可以看到,我们可以使用forEach()方法来遍历JavaScript数组,并传入一个回调函数。