I wanted to copy one JavaScript element from an array into another array and then edit some of its properties. the specific code I used was:
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>"
}
What is supposed to happen is that a new element gets added to the friends
array that is the same as one of the elements in the enemies
array. Then the player is allowed to enter a new name for that element in the friends
array. Since the drops, part of the element is no longer necessary I wanted to replace it with the original name for future use. What actually happens is that both the enemies
element and the friends
element get edited to be the same. I don't understand why.
There may be something else happening while I am editing stuff, but that seems unlikely. I have checked and found nothing, but if you want to take a look the full code can be found here. The files that are being used in this example are friend.js
and globalvars.js
. In addition, battle.js
and explore.js
are also involved here. battle.js
leads to friend.js
being called and then the friends
array is used in explore.js.
I am interested in knowing how JavaScript elements behave when duplicated and if there is a way to do this without editing the element in the enemies
array.
Edit: Changed every instance of JSON to JavaScript because I was wrong in thinking that this was JSON.