用于遍历数组,无返回值
let arr = [1, 2, 3, 4];
arr.forEach(function(item,index,array){
array[index]=item*2;
})
console.log(arr);//[2, 4, 6, 8]
可以看到,forEach()可以传入一个匿名函数作为参数,而该匿名函数有含有三个参数,其依次代表数组遍历时的当前元素item,数组遍历时的当前元素的索引index,以及正在遍历的数组array。有了这三个参数,可以方便我们做很多事情,比如说示例当中将每一项数组元素翻倍,这时需要用到第一个参数item。但是,仅仅只是将item乘以2可不行,我们还得将其赋值给原来的数组,这时我们就得用到后面两个参数index和array。
根据上述可知,array[index]是全等于item的。
arr.forEach(function(item,index,array){
console.log(array[index] === item); // true
});