2013-06-04 48 views
5

我正在閱讀John ResigLearning 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

這讓我想知道爲什麼需要另一個參數?

+0

這只是爲了方便。您可能想在循環內打印「i」。 – elclanrs

回答

1

在正常for循環中,正文可以訪問索引i。如果回調解決方案是爲了取代這個,它應該也有這個信息。例如,它可能對創建唯一標識符很有用。所以我們把它作爲參數傳遞。