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));
});
我不完全理解为什么这里使用null
。我想当我使用invoke foreach
时,如果我错过了context
参数,它会用null
替换它? callback.call(context || null, this[i], i, this)
会执行吗?有人可以帮我解释一下吗?
最佳答案
它实际上不应该在那里。当作为 this
参数传递给 Function.prototype.call
(函数的 code>this
参数设置为 undefined
)。
关于javascript - 这段 javascript 代码中为 null 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18093605/