遍历数组
let arr = [1, 2, 3, 4]
/**
* forEach() 方法对数组的每个元素执行一次提供的函数。
* params: callback
* params: thisArg 当执行回调函数时用作 this 的值(参考对象)。
* return undefined forEach总是返回undefined且不可链式调用,一般放链式最后。
*/
arr.forEach(callback, this) // forEach()为数组中的每一个元素执行一次callback
/**
* callback为数组中每个元素执行的函数,该函数接收三个参数:
* params: currentValue 数组中正在处理的当前元素。
* params: index(可选) 数组中正在处理的当前元素的索引。
* params: array(可选) forEach() 方法正在操作的数组。
*/
function callback(currentValue, index, array) {
console.log(currentValue) // 1 2 3 4
console.log(index) // 0 1 2 3
console.log(array) // [1,2,3,4] [1,2,3,4] [1,2,3,4] [1,2,3,4]
}
// 注意索引 3 被跳过了,因为在数组的这个位置没有项
[1, 2, 3, , 4].forEach(callback)
// currentValue 1 2 3 4
// index 0 1 2 4
// array [1, 2, 3, empty, 4]
如果数组在迭代时被修改了
forEach 遍历的范围在第一次调用 callback 前就会确定。
调用 forEach 后添加到数组中的项不会被 callback 访问到。
// forEach 遍历的范围在第一次调用 callback 前就会确定。
// 调用 forEach 后添加到数组中的项不会被 callback 访问到。
arr.forEach(function(currentValue) {
if(currentValue === 2) {
arr.push(5)
}
console.log(currentValue) // 1 2 3 4
})
console.log(arr) // [1,2,3,4,5]
arr2在遍历到b时,删除了第一项,导致剩下的项移一个位置
forEach()不会在迭代之前创建数组的副本。
// arr在遍历到b时,删除了第一项,导致剩下的项移一个位置
// forEach()不会在迭代之前创建数组的副本。
let arr2 = ['a', 'b', 'c', 'd']
arr2.forEach(function(currentValue) {
if(currentValue === 'b') {
arr2.shift()
}
console.log(currentValue) // a b d
})
console.log(arr2) // b c d
使用thisArg
forEach若不传this,callback里的this在非严格模式指向window,严格模式为undefined
function Counter() {
this.sum = 0;
this.count = 0;
}
Counter.prototype.add = function(array) {
array.forEach(function(entry) {
this.sum += entry;
++this.count;
}, this); // 若不传this,forEach里的this在非严格模式指向window,严格模式为undefined
console.log(this === obj); // true
};
var obj = new Counter();
obj.add([1, 3, 5, 7]);
obj.count;
// 4 === (1+1+1+1)
obj.sum;
// 16 === (1+3+5+7)
注意:没有办法中止或者跳出 forEach() 循环
若你需要提前终止循环,你可以使用:
网友评论