如何将JavaScript对象从一个数组复制到另一个数组?

时间:2020-02-08 03:15:59

标签: javascript arrays

我想将一个 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.jsglobalvars.js。此外,此处还涉及battle.jsexplore.jsbattle.js导致调用friend.js,然后在Explore.js中使用friends数组。

我想知道JavaScript元素在复制时的行为,以及是否有一种无需编辑enemies数组中的元素的方式。

编辑:将 JSON 的每个实例更改为 JavaScript ,因为我认为这是 JSON 是错误的

1 个答案:

答案 0 :(得分:-1)

JavaScript对象无法复制。相反,所有可能的副本都链接回原始文件。您必须对具有所需值的新对象进行硬编码,以使其不链接到原始对象。例如:

let f={
     name: "namehere",
     secondAttribute: 0
}
let r={
    name: f.name,
    secondAttribute: f.secondAttribute
}
即使

r具有相同的属性,也不会链接到f。您可以编辑r或f而无需更改其他参数。