gpt4 book ai didi

Javascript 在没有引用的情况下插入数组

转载 作者:行者123 更新时间:2023-11-29 23:28:10 25 4
gpt4 key购买 nike

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

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

关于Javascript 在没有引用的情况下插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48292522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com