2

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

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,输出

4

3 回答 3

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

于 2018-01-17T02:30:08.973 回答
1

问题的解决方案:

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

于 2018-01-18T21:10:52.510 回答
0

您可以使用名为“组”的函数作为构造函数。

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/>");

    });

});
于 2018-01-18T21:19:59.520 回答