3 回答
![?](http://img1.sycdn.imooc.com/545868190001d52602200220-100-100.jpg)
TA贡献1871条经验 获得超13个赞
i不会成为迭代器。在代码中,您使用 es6 速记符号来描述函数。i是函数的唯一参数。
i => {
labels.push(`Unit ${i + 1}`);
});
是相同的
function(i){
labels.push(`Unit ${i + 1}`);
}
请在此参考中查看有关速记符号的更多信息
编辑:要回答您的评论“添加了什么”,您必须repeat(n, action)更仔细地查看该功能。i在这两种情况下都使用它也可能会让您感到困惑,因此我将重写该函数以帮助您理解。此函数使用 for 循环从 0 到n
for (let idx = 0; idx < n; idx++) {
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值没有引用内存中的相同值,可以像我在解释中所做的那样重命名
![?](http://img1.sycdn.imooc.com/545862e700016daa02200220-100-100.jpg)
TA贡献1712条经验 获得超3个赞
将您i用作for循环中的变量以及箭头函数的参数有点令人困惑。将函数参数更改为x并查看它仍然有效,可能会导致更好地理解变量范围并使其更易于解释:
repeat(5, x => {
labels.push(`Unit ${x + 1}`);
});
您正在将箭头函数传递给repeat()函数。在 repeat 函数内部,for循环i在每次迭代中增加,在本例中从 0 到 4,并且每次都调用您作为action参数传递的箭头函数。此函数的x参数将采用 的值i,因为您在调用action引用(即箭头函数)时将其作为第一个参数传递。
![?](http://img1.sycdn.imooc.com/545865890001495702200220-100-100.jpg)
TA贡献2036条经验 获得超8个赞
在repeat函数中,您将 forloop 索引传递给回调
function repeat(n, action) {
for (let i = 0; i < n; i++) {
action(i); // here you are passing index to callback
}
}
并且您将索引作为参数
repeat(5, i => { // Here you will get params that is passed by repeat function
labels.push(`Unit ${i + 1}`);
});
希望这会有所帮助
添加回答
举报