我想将一个 JavaScript 元素从一个数组复制到另一个数组,然后编辑其某些属性。我使用的特定代码是:
var friends=[]
var enemies=[
{
name: "Slime",
health: 20,
attack: 10,
defense: 15,
speed: 5,
drops: {name: "Vial of Blood", chance: 10, type: "consumable", id: 0},
friendable: {possible: false}
},
{
name: "Bat",
health: 15,
attack: 5,
defense: 10,
speed: 20,
drops: {name: "Speedy Vial", chance: 5, type: "consumable", id: 1},
friendable: {possible: true, item: 0}
}
]
function dofriend(num11,num12) {
let protype=enemies[num12]
sack.splice(num11,1)
invid.splice(num11,1)
invtype.splice(num11,1)
friends.push(protype)
friends[friends.length-1].drops=protype.name
friends[friends.length-1].name=prompt("Pick a name for your friend.",protype.name)
battlechk=false;
document.getElementById("textbox").innerText="You befriended "+friends[friends.length-1].name+"!"
document.getElementById("optionbox").innerHTML="<button class=\"option\" onclick=\"cancel()\">Yay!</button>"
}
应该发生的是,一个新元素被添加到friends
数组中,该元素与enemies
数组中的元素之一相同。然后,允许播放器在friends
数组中为该元素输入新名称。由于删除了这些元素,因此不再需要该元素的一部分,因此我想将其替换为原始名称以供将来使用。实际发生的是enemies
元素和friends
元素都被编辑为相同。我不明白为什么。
我在编辑内容时可能还会发生其他事情,但这似乎不太可能。我已经检查并没有发现任何内容,但是如果您想查看完整的代码can be found here。本示例中使用的文件是friend.js
和globalvars.js
。此外,此处还涉及battle.js
和explore.js
。 battle.js
导致调用friend.js
,然后在Explore.js中使用friends
数组。
我想知道JavaScript元素在复制时的行为,以及是否有一种无需编辑enemies
数组中的元素的方式。
编辑:将 JSON 的每个实例更改为 JavaScript ,因为我认为这是 JSON 是错误的
答案 0 :(得分:-1)
JavaScript对象无法复制。相反,所有可能的副本都链接回原始文件。您必须对具有所需值的新对象进行硬编码,以使其不链接到原始对象。例如:
let f={
name: "namehere",
secondAttribute: 0
}
let r={
name: f.name,
secondAttribute: f.secondAttribute
}
即使r具有相同的属性,也不会链接到f。您可以编辑r或f而无需更改其他参数。