forEach()简介
forEach() 方法按升序为数组中含有效值的每一项执行一次 callback 函数,那些已删除或者未初始化的项将被跳过(例如在稀疏数组上)。
forEach
是ES6新增的Array内置方法,它可以遍历js数组,并为其中的每个元素都执行特定的回调函数。forEach
方法接受两个参数- callback: 第一个参数是一个回调函数,该回调函数接收三个参数
- item: 当前遍历到的数组元素
- index(可选): 当前遍历到的索引
- array(可选): 当前数组本身
- thisArg(可选): 第二个参数指定了执行callback的时候,用作this的值
- 例子
var arr = [1, 2, 3], obj = { name: 'zs' } arr.forEach(function (item, index, array) { console.log('item: ', item, 'index: ', index, 'array: ', array, 'this: ', this) }, obj) // item: 1 index: 0 array: (3) [1, 2, 3] this: {name: "zs"} // item: 2 index: 1 array: (3) [1, 2, 3] this: {name: "zs"} // item: 3 index: 2 array: (3) [1, 2, 3] this: {name: "zs"}
- callback: 第一个参数是一个回调函数,该回调函数接收三个参数
- 在使用
forEach
时有以下几点需要注意forEach()
遍历的范围在第一次调用 callback 前就会确定forEach()
被调用时,不会改变原数组,但callback函数可能会改变原数组forEach()
循环除了抛出异常外,无法终止forEach()
不对未初始的值进行任何操作 — [1, 2, , 4].forEach()只会遍历到1, 2, 4
- 如果对上述要注意的地方还是不大明白的话,接下来我们手动实现一个forEach,就可以搞清楚了
手写forEach
// forEach接收两个参数,一个是回调函数,一个指定了执行回调函数时的this
Array.prototype.myForEach = function (callbackFunc, thisArg) {
var T, k;
var O = Object(this)
// 这里指定了forEach()的范围,也就是上述注意的第一点
var len = O.length
// 如果存在第二个参数,也就是thisArg,就赋值给T
if (arguments.length > 1) {
T = thisArg
}
k = 0
while (k < len) {
var kValue
// 如果存在第k项,因为有可能之前执行的回调函数改变了数组
if (k in O) {
kValue = O[k]
// 通过call来改变canllbackFunc执行时的this
callbackFunc.call(T, kValue, k, O)
}
k++
}
}