说明
它已经在documentation 中(重点是我的):
15.4.4.18 Array.prototype.forEach ( callbackfn [ , thisArg ] )
callbackfn 应该是一个接受三个参数的函数。
forEach 调用 callbackfn 一次
数组,按升序排列。 callbackfn 仅针对以下元素调用
实际存在的数组;不需要缺少元素
数组。
如果提供了thisArg参数,它将被用作this
每次调用 callbackfn 的值。如果没有提供,
改为使用undefined。
thisArg 仅用于callbackfn 的调用。但是,它不用于为forEach 提供this 值,其中this 需要是一个类似数组的结构(这意味着它具有length 属性)。如果你使用Array.prototype.forEach(..., someObject),this 在forEach 的上下文中的值将是undefined。
简化版forEach(即刻显示问题)
function forEach( callback , thisArg ){
// The algorithm parses the length as UInt32, see step 3.
// >>> not only acts as bit shift, but also forces the
// value into an unsigned number.
var len = this.length >>> 0, // using "this", not "thisArg"!
i;
for(i = 0; i < len; ++i){
callback.call(thisArg, this[i]);
// thisArg ^^^^^^^^^ is used here, not up at length
}
}
// example calls:
var logArguments = function(args){
console.log(args, this);
}
forEach(logArguments, [1,2,3]); // logs nothing
forEach.call([1,2,3], logArguments); // logs 1, 2, 3
forEach.call([1,2,3], logArguments, [2,3,4]); // logs "1 Array [2,3,4]"
// "2 Array [2,3,4]"
// "3 Array [2,3,4]"