简体   繁体   中英

Javascript/Angular is modifying my constant variable even thought i do not ask him to

i have a recent problem on Javascript/Angular and i haven't found a solution yet.

var listPlayers = $rootScope.Party.players;
$rootScope.Party.order = $scope.randomTeam(listPlayers);    

This is a function that will random the order of the players

$scope.randomTeam = function(players){
    var team = players;
    var order = [];
    var index = team.length;
    l = team.length;

    for (var i = 0; i < l; i++) {
        var alea = randomNumber(0,index-1);
        order.push(team[alea]);
        team.splice(alea,1);

        index--;
    }
    return order;
}

Player list look like this :

 $rootScope.Party = {
    players: [
        {name:'John', id:1},
        {name:'Peter', id:2},
        {name:'Daniel', id:3},

    ],
    order: [],
}

At the end:

 $rootScope.Party = {
    players: [],
    order: [{name:'Peter', id:1},
        {name:'Peter', id:2},
        {name:'John', id:3},]
 }

My "players" list became empty and i don't know why

AND even thought i didn't alter my $rootScope.Party.players, the function manage to empty the table and $rootScope.Party.players is empty at the end of the function. This realy enrage me because i put it in an other variable and put that variable as a parameter for the function.

Your problem is at var team = players;

Changing team variable will change players as javascript by default maintains old references.

Try using var team = players.slice();

It would create the new copy of players and changing team won't affect players.

Hope it helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM