javascript代码中的null? Array.prototype.forEach=函数(回调,上下文){ for(var i=0;i
我不完全理解为什么这里使用javascript代码中的null? Array.prototype.forEach=函数(回调,上下文){ for(var i=0;i,javascript,Javascript,我不完全理解为什么这里使用null。我猜当我使用invokeforeach时,如果我错过了context参数,它将替换为null?调用(上下文| | null,this[i],i,this)执行吗?有人能给我解释一下吗?如果您为“context”传递一个错误的值,(context | null)将导致null。JS将null作为第一个参数传递到callback.call()中。第一个参数是回调函数的this。它实际上不应该在那里undefined和null与this参数传递给Function.p
null
。我猜当我使用invokeforeach
时,如果我错过了context
参数,它将替换为null
?调用(上下文| | null,this[i],i,this)执行吗?有人能给我解释一下吗?如果您为“context”传递一个错误的值,(context | null)
将导致null。JS将null作为第一个参数传递到callback.call()
中。第一个参数是回调函数的this
。它实际上不应该在那里undefined
和null
与this
参数传递给Function.prototype.call
(函数的this
参数设置为undefined
)时具有相同的效果。因此,即使我将null或undefined传递给Function.prototype.call,Function.prototype.call仍然可以执行?@joesmith:this参数可以接受任何值。在非严格模式下,如果将null
或undefined
作为this
参数传递,则函数中的this
将是undefined
。
Array.prototype.forEach = function(callback, context) {
for (var i = 0; i < this.length; i++) {
callback.call(context || null, this[i], i, this);
}
};
["a", "b", "c"].forEach(function(value, index, array) {
assert(value,
"Is in position " + index + " out of " +
(array.length - 1));
});