从多个相同的阵列中删除一个项目

时间:2015-12-15 11:54:58

标签: javascript

我正在尝试从完全相同的数组中删除项目。有趣的是,它在我的阵列不同时起作用。以下代码按预期工作,从team1删除Fireman,从team2删除Pyromancer,从team3删除Aronist,从team4删除Vigilante。

var options = {};
options.characters = ["Fireman","Missionary","Vigilante","Corrupt Policeman","Suicide Bomber","Arsonist","Gunman","Pyromancer","Hypnotist","Picklock","Policeman","Child","Prostitute"];
this._team1Characters = options.characters.concat(["test1"]);
this._team2Characters = options.characters.concat(["test2"]);
this._team3Characters = options.characters.concat(["test3"]);
this._team4Characters = options.characters.concat(["test4"]);
var submissions = {};
submissions.character1 = "Fireman";
submissions.character2 = "Pyromancer";
submissions.character3 = "Arsonist";
submissions.character4 = "Vigilante";
var i = 5;
    while(--i){

        if(submissions["character"+i]){ 

            this["_team"+i+"Characters"].splice( this["_team"+i+"Characters"].indexOf(submissions["character"+i]), 1 );            
        }
    }
alert(this._team1Characters);
alert(this._team2Characters);
alert(this._team3Characters);
alert(this._team4Characters);

但是,如果四个阵列相同,则所有阵列都相同(都缺少Fireman,Pyromancer,Aronist和Vigilante)。这是导致问题的代码:

var options = {};
options.characters = ["Fireman","Missionary","Vigilante","Corrupt Policeman","Suicide Bomber","Arsonist","Gunman","Pyromancer","Hypnotist","Picklock","Policeman","Child","Prostitute"];
this._team1Characters = options.characters; 
this._team2Characters = options.characters;
this._team3Characters = options.characters;
this._team4Characters = options.characters;
var submissions = {};
submissions.character1 = "Fireman";
submissions.character2 = "Pyromancer";
submissions.character3 = "Arsonist";
submissions.character4 = "Vigilante";
var i = 5;
    while(--i){

        if(submissions["character"+i]){ 

            this["_team"+i+"Characters"].splice( this["_team"+i+"Characters"].indexOf(submissions["character"+i]), 1 );
        }
    }
alert(this._team1Characters);
alert(this._team2Characters);
alert(this._team3Characters);
alert(this._team4Characters);

原因是什么?

2 个答案:

答案 0 :(得分:3)

当您执行this._team1Characters = options.characters;时,您正在传递引用,因此您最终会获得对同一数组的大量引用。因此,当您更改该单个数组时,您将通过任何引用看到更改。

如果要复制数组,请使用Array.prototype.slice()

this._team1Characters = options.characters.slice();
...

答案 1 :(得分:2)

因为您要将同一个变量的引用分配给all,所以所有删除都基本上来自同一个数组options.characters

尝试这样做

this._team1Characters = options.characters.concat( [] ); 
this._team2Characters = options.characters.concat( [] );
this._team3Characters = options.characters.concat( [] );
this._team4Characters = options.characters.concat( [] );

这将确保所有在不同数组中获取相同的值,并且从一个数组中删除时,其他数组中的值不受影响