我正在阅读John Resig的Learning Advanced JavaScript幻灯片。
当我来到第27 张幻灯片时,约翰提出了一个测验,如下所示:
测验:我们如何使用回调实现循环?
function loop(array, fn){
for ( var i = 0; i < array.length; i++ ) {
// Implement me!
}
}
var num = 0;
loop([0, 1, 2], function(value){
assert(value == num++, "Make sure the contents are as we expect it.");
assert(this instanceof Array, "The context should be the full array.");
});
我试图实现,并想出了以下代码:
function loop(array, fn){
for ( var i = 0; i < array.length; i++ ) {
fn.call(array, array[i]);
}
}
var num = 0;
loop([0, 1, 2], function(value){
assert(value == num++, "Make sure the contents are as we expect it.");
assert(this instanceof Array, "The context should be the full array.");
});
我很高兴它成功了,并渴望看到下一张幻灯片,将它与约翰将在下一张幻灯片中提供的解决方案进行比较。
但在下一张幻灯片中,约翰提供了以下解决方案:
function loop(array, fn){
for ( var i = 0; i < array.length; i++ )
fn.call( array, array[i], i );
}
var num = 0;
loop([0, 1, 2], function(value, i){
assert(value == num++, "Make sure the contents are as we expect it.");
assert(this instanceof Array, "The context should be the full array.");
});
对于他传递给的 fn 函数loop()
,他添加了另一个参数i
。
这让我想知道为什么需要另一个参数?