Javascript pushing objects into array changes entire array

前端 未结 8 2309
借酒劲吻你
借酒劲吻你 2020-12-03 08:48

I\'m using a specific game making framework but I think the question applies to javascript

I was trying to make a narration script so the player can see \"The orc hi

相关标签:
8条回答
  • 2020-12-03 09:16

    I do not know why a JSON way of doing this has not been suggested yet. You can first stringify the object and then parse it again to get a copy of the object.

    let uniqueArr = [];
    let referencesArr = [];
    let obj = {a: 1, b:2};
    
    uniqueArr.push(JSON.parse(JSON.stringify(obj)));
    referencesArr.push(obj);
    
    obj.a = 3;
    obj.c = 5;
    uniqueArr.push(JSON.parse(JSON.stringify(obj)));
    referencesArr.push(obj);
    
    //You can see the differences in the console logs
    console.log(uniqueArr);
    console.log(referencesArr);

    0 讨论(0)
  • 2020-12-03 09:17

    As mentioned multiple times above, the easiest way of doing this would be making it a string and converting it back to JSON Object.

    this.<JSONObjectArray>.push(JSON.parse(JSON.stringify(<JSONObject>)));
    

    Works like a charm.

    0 讨论(0)
提交回复
热议问题