Javascript pushing objects into array changes entire array

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

    When you push servermessage into servermessagelist you're really (more or less) pushing a reference to that object. So any changes made to servermessage are reflected everywhere you have a reference to it. It sounds like what you want to do is push a clone of the object into the list.

    Declare a function as follows:

    function cloneMessage(servermessage) {
        var clone ={};
        for( var key in servermessage ){
            if(servermessage.hasOwnProperty(key)) //ensure not adding inherited props
                clone[key]=servermessage[key];
        }
        return clone;
    }
    

    Then everytime you want to push a message into the list do:

    servermessagelist.push( cloneMessage(servermessage) );
    

提交回复
热议问题