简体   繁体   English

Javascript / Angular正在修改我的常量变量,即使我不要求他

[英]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. 我最近在Javascript / Angular上遇到问题,但尚未找到解决方案。

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. 甚至以为我没有更改$ rootScope.Party.players,该函数设法清空表,而$ rootScope.Party.players在函数末尾为空。 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; 您的问题在于var team = players;

Changing team variable will change players as javascript by default maintains old references. 更改团队变量会更改玩家,因为javascript默认情况下会保留旧的引用。

Try using var team = players.slice(); 尝试使用var team = players.slice();

It would create the new copy of players and changing team won't affect players. 它将创建新的玩家副本,并且更换团队不会影响玩家。

Hope it helps!! 希望能帮助到你!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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