Javascript推送到数组而没有引用

时间:2018-01-17 01:52:04

标签: javascript arrays shadow-copy

这对我来说非常令人沮丧,所以我希望有人可以提供帮助。下面是一个小例子来说明我的问题。

var group = {
    names: []
}
var groupList = {
    group: [],
    activity:[]
}

$(document).ready(function(){

    $("#play").click(function(){

        var soccer = group;

        var person = "Jack";
        soccer.names.push(person);

        var person = "Amber";
        soccer.names.push(person)

        groupList.group.push(soccer); //group[0]

        // how do I make a constructor for a new group?
        var soccer1 = group;
        var person = "Jill";
        soccer1.names.push(person)

        groupList.group.push(soccer1); //group[1]

        // expect group 0 to be [Jack,Amber] (but pushing Jill on group1 updates group0)
        $("#beta").append("Soccer Group: "+groupList.group[0].names +"<br/>");

         // expect group 1 to be either [Jack,Amber,Jill] or [Jill]
        $("#beta").append("Soccer Group: "+groupList.group[1].names +"<br/>");

    });

});

我需要在不更改原始组的情况下创建组的新实例。

https://jsbin.com/hetenol/edit?html,js,output

3 个答案:

答案 0 :(得分:1)

编辑:以下内容仅在您计划使用基元填充数组Game.playerGame.score时才有效。

您可以像这样克隆数组:

AllGames.games.push({
  player: [...Game.player],
  score: [...Game.score]
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator

答案 1 :(得分:0)

问题的解决方案:

var soccer1 = jQuery.extend(true,{},group);

答案 2 :(得分:0)

您可以使用名为&#34; group&#34;作为构造者。

function group() {
    this.names = [];
}

var groupList = {
    group: [],
    activity:[]
}

$(document).ready(function(){

$("#play").click(function(){

    var soccer, soccer1, person;

    soccer = new group();

    person = "Jack";
    soccer.names.push(person);

    person = "Amber";
    soccer.names.push(person)

    groupList.group.push(soccer); //group[0]

    soccer1 = new group();
    person = "Jill";
    soccer1.names.push(person)

    groupList.group.push(soccer1); //group[1]

    // expect group 0 to be [Jack,Amber]
    $("#beta").append("Soccer Group: "+groupList.group[0].names +"<br/>");

     // expect group 1 to be [Jill]
    $("#beta").append("Soccer 1 Group: "+groupList.group[1].names +"<br/>");

    });

});