Javascript在没有引用的情况下推送到数组中



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

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

编辑:仅当您计划用基元填充数组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

问题的解决方案:

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

您可以使用名为"group"的函数作为构造函数。

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

相关内容

  • 没有找到相关文章

最新更新