javascript - 函数循环的可能解决方案

标签 javascript function loops

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

当我来到slide-27 , john 提出了一个测验如下:

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

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

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

最佳答案

在普通的for 循环中,循环体可以访问索引i。如果回调解决方案旨在替代此解决方案,则它也应该提供此信息。例如,它可能对创建唯一标识符很有用。所以我们将其作为参数传递。

关于javascript - 函数循环的可能解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16913865/

相关文章:

javascript - 谷歌地图 API : Cannot read property '__e3_' of undefined

r - 在 addmargins 函数上自定义 "Sum"标签

javascript - 如何使用 for 循环向 JS 变量添加值?

c - 我的 for 循环出了什么问题?

javascript - node.js 中的模块 passport-oauth2 : extra parameters to be included in the authorization request

javascript - Uncaught ReferenceError : (given function) is not defined

c++ - 如何将对象作为参数传递给类

java - 了解 do-while 循环

loops - 了解循环不变式。寻找并证明它们的算法

javascript - 单个应用程序中的 Dotcloud www 和 TCP -