Javascript pushing objects into array changes entire array

前端 未结 8 2364
借酒劲吻你
借酒劲吻你 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:01

    There are two ways to use deep copy the object before pushing it into the array. 1. create new object by object method and then push it.

    servermessagelist = []; 
    servermessagelist.push(Object.assign({}, servermessage));
    
    1. Create an new reference of object by JSON stringigy method and push it with parse method.

      servermessagelist = []; servermessagelist.push(JSON.parse(JSON.stringify(servermessage));

    This method is useful for nested objects.

提交回复
热议问题