Javascript pushing objects into array changes entire array

前端 未结 8 2361
借酒劲吻你
借酒劲吻你 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);

提交回复
热议问题