forEach()方法需要一个回调函数(这种函数,是由我们创建但是不由我们调用的)作为参数
回调函数中传递三个参数:
- 第一个参数,就是当前正在遍历的元素
- 第二个参数,就是当前正在遍历的元素的索引
- 第三个参数,就是正在遍历的数组
例子
let myArr = ['王一', '王二', '王三'];
myArr.forEach((item, index, arr) => {
console.log('item:' + item);
console.log('index:' + index);
console.log('arr:' + JSON.stringify(arr));
});
打印输出结果:
item:王一
index:0
arr:["王一","王二","王三"]
----------
item:王二
index:1
arr:["王一","王二","王三"]
----------
item:王三
index:2
arr:["王一","王二","王三"]
----------