5
我正在閱讀John Resig的Learning Advanced JavaScript幻燈片。功能循環的可能解決方案
正如我來到slide-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.");
});
到他傳遞給loop()
將fn的功能,他加入另一參數i
。
這讓我想知道爲什麼需要另一個參數?
這只是爲了方便。您可能想在循環內打印「i」。 – elclanrs