3 回答

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值沒有引用內存中的相同值,可以像我在解釋中所做的那樣重命名

TA貢獻1712條經驗 獲得超3個贊
將您i用作for循環中的變量以及箭頭函數的參數有點令人困惑。將函數參數更改為x并查看它仍然有效,可能會導致更好地理解變量范圍并使其更易于解釋:
repeat(5, x => {
labels.push(`Unit ${x + 1}`);
});
您正在將箭頭函數傳遞給repeat()函數。在 repeat 函數內部,for循環i在每次迭代中增加,在本例中從 0 到 4,并且每次都調用您作為action參數傳遞的箭頭函數。此函數的x參數將采用 的值i,因為您在調用action引用(即箭頭函數)時將其作為第一個參數傳遞。

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}`);
});
希望這會有所幫助
添加回答
舉報