功能循环的可能解决方案

时间:2013-06-04 09:10:15

标签: javascript function loops

我正在阅读John ResigLearning Advanced JavaScript幻灯片。

当我来到slide-27时,约翰提出了一个测验,如下所示:

QUIZ:我们如何使用回调实现循环?

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.");
});

我很高兴它有效,并且渴望看到下一张幻灯片与解决方案john进行比较将在下一张幻灯片中提供。

但是在下一张幻灯片中,约翰提供了以下解决方案:

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

这让我想知道为什么需要另一个参数?

1 个答案:

答案 0 :(得分:1)

在正常的for循环中,正文可以访问索引i。如果要将回调解决方案替换为此,则还应提供此信息。例如,它可用于创建唯一标识符。所以我们将它作为参数传递。

相关问题