这种抽象的重复是如何工作的?

我正在阅读一些 Javascript 内容,因为我梦想成为一名优秀的 JS 开发人员。我有点知道如何使用基础知识来满足我的 PHP 需求,但仍有一些疑问。


我看到了一些例子并得到了这个:


function repeat(n, action) {

   for (let i = 0; i < n; i++) {

      action(i);

   }

}


let labels = [];


repeat(5, i => {

   labels.push(`Unit ${i + 1}`);

});


console.log(labels);

所以,如果需要,我可以用它来重复一些基本功能。理解,但在另一种情况下,我可以通过一些不同的方法使用相同的功能。

如果我想传递一个函数,为什么变量i会变成计数器/迭代器?

我以前一直使用它,但仍然不知道它是如何工作的,所以我不能在真正需要的时候使用它。


喵喔喔
浏览 127回答 3
3回答

慕桂英4014372

i不会成为迭代器。在代码中,您使用 es6 速记符号来描述函数。i是函数的唯一参数。i => {&nbsp; &nbsp;labels.push(`Unit ${i + 1}`);});是相同的function(i){&nbsp; labels.push(`Unit ${i + 1}`);}&nbsp;请在此参考中查看有关速记符号的更多信息编辑:要回答您的评论“添加了什么”,您必须repeat(n, action)更仔细地查看该功能。i在这两种情况下都使用它也可能会让您感到困惑,因此我将重写该函数以帮助您理解。此函数使用 for 循环从 0 到nfor (let idx = 0; idx < n; idx++) {&nbsp; &nbsp;action(idx);}并使用当前的 for 循环索引调用操作idx。所以你的例子:Iteration 0: action(0) -> labels.push(`Unit ${0 + 1}`);Iteration 1: action(1) -> labels.push(`Unit ${1 + 1}`);Iteration 2: action(2) -> labels.push(`Unit ${2 + 1}`);Iteration 3: action(3) -> labels.push(`Unit ${3 + 1}`);Iteration 4: action(4) -> labels.push(`Unit ${4 + 1}`);请你注意,repeat的的声明i是局部的它的功能体,就像i在i => { labels.push(单位$ {I + 1}); }是本地的函数体。这两个i值没有引用内存中的相同值,可以像我在解释中所做的那样重命名

交互式爱情

将您i用作for循环中的变量以及箭头函数的参数有点令人困惑。将函数参数更改为x并查看它仍然有效,可能会导致更好地理解变量范围并使其更易于解释:repeat(5, x => {&nbsp; &nbsp;labels.push(`Unit ${x + 1}`);});您正在将箭头函数传递给repeat()函数。在 repeat 函数内部,for循环i在每次迭代中增加,在本例中从 0 到 4,并且每次都调用您作为action参数传递的箭头函数。此函数的x参数将采用 的值i,因为您在调用action引用(即箭头函数)时将其作为第一个参数传递。

慕桂英3389331

在repeat函数中,您将 forloop 索引传递给回调function repeat(n, action) {&nbsp; &nbsp;for (let i = 0; i < n; i++) {&nbsp; &nbsp; &nbsp; action(i); // here you are passing index to callback&nbsp; &nbsp;}}并且您将索引作为参数repeat(5, i => { // Here you will get params that is passed by repeat function&nbsp; &nbsp;labels.push(`Unit ${i + 1}`);});希望这会有所帮助
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript