1

In this code, I add an action for a "bet", and pass its id as a parameter to a function. But when I call this arrow function later, the argument of this.undoBet equals to this.local_bets[this.local_bets.length].bet_id - the last bet_id that was passed inside the loop.

How to make it so that inside every arrow function, this.undoBet would preserve the bet_id assigned to it in that loop?

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 );
        });

    }

}

3 Answers 3

3

A common JavaScript mistake. Its because for (var k in this.local_bets) { the index will actually be the last one by the time the continuing function executes.

Fix

use let:

for (let k in this.local_bets) {

    let bet = this.local_bets[k];

More

This is covered here https://basarat.gitbooks.io/typescript/content/docs/let.html 🌹

Sign up to request clarification or add additional context in comments.

Comments

2

Try this (another local variable will be scoped in the each new undo bet function):

this.local_bets
    .filter(bet => bet.status == BetStatus.accepted)
    .forEach(bet => this.addUndo("undo_bet", () => this.undoBet(bet.bet_id)));

1 Comment

Although I find function chining more elegant, I used a dictionary here, so it wouldn't work. Thanks for the suggestion though!
0

All solutions are good, but better is to use const keyword when variable is not supposed to change. Check the code below:

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 );
    });

}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.