在此代码中,我为“bet”添加了一个动作,并将其id作为参数传递给函数。但是当我稍后调用此箭头函数时,this.undoBet
的参数等于this.local_bets[this.local_bets.length].bet_id
- 循环内传递的最后一个bet_id
。
如何使它在每个箭头函数内部this.undoBet
保留在该循环中分配给它的bet_id
?
for (var k in this.local_bets) {
var bet = this.local_bets[k];
if (bet.status == BetStatus.accepted) {
// Here bet_id is correct for every "bet" variable
this.addUndo( "undo_bet", () => {
// When calling this later, bet_id equals to one that belongs to the last bet inside this.local_bets
this.undoBet( bet.bet_id );
});
}
}
答案 0 :(得分:3)
一个常见的JavaScript错误。因为for (var k in this.local_bets) {
索引在执行连续函数时实际上是 last 。
使用let
:
for (let k in this.local_bets) {
let bet = this.local_bets[k];
此处包含https://basarat.gitbooks.io/typescript/content/docs/let.html
答案 1 :(得分:2)
尝试这个(另一个局部变量将在每个新的撤消投注功能中确定范围):
this.local_bets
.filter(bet => bet.status == BetStatus.accepted)
.forEach(bet => this.addUndo("undo_bet", () => this.undoBet(bet.bet_id)));
答案 2 :(得分:0)
所有解决方案都不错,但是最好是在不应该更改变量的情况下使用 const
关键字。检查以下代码:
for (const k in this.local_bets) {
const bet = this.local_bets[k];
if (bet.status == BetStatus.accepted) {
// Here bet_id is correct for every "bet" variable
this.addUndo( "undo_bet", () => {
// When calling this later, bet_id equals to one that belongs to the last bet inside this.local_bets
this.undoBet( bet.bet_id );
});
}
}