JavaScript的对象推到数组改变整个数组 [英] Javascript pushing objects into array changes entire array

查看:183
本文介绍了JavaScript的对象推到数组改变整个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个特定的游戏制作框架,但我认为这个问题适用于JavaScript的

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

我试图让旁白脚本,以便玩家可以看到兽人打你。在他的屏幕的底部。我想在同一时间显示最后4条消息,可能让玩家回头看到在日志30-50消息,如果他们想。要做到这一点,我设置和对象和数组对象推入。

I was trying to make a narration script so the player can see "The orc hits you." at the bottom of his screen. I wanted to show the last 4 messages at one time and possibly allow the player to look back to see 30-50 messages in a log if they want. To do this I set up and object and an array to push the objects into.

所以我设置了一些变量,像这样的开始......

So I set up some variables like this initially...

servermessage: {"color1":"yellow", "color2":"white", "message1":"", "message2":""},
servermessagelist: new Array(),

,当我通过操纵servermessage.color1使用此命令(下图)多次通过一个事件称为不同的数据... .message1等等...

and when I use this command (below) multiple times with different data called by an event by manipulating servermessage.color1 ... .message1 etc...

servermessagelist.push(servermessage)

它会覆盖与数据拷贝整个数组...任何想法,为什么和我能做些什么了。

it overwrites the entire array with copies of that data... any idea why or what I can do about it.

所以,如果我把颜色1红,MESSAGE1罗浮..数据是正确的话,如果我推
COLOR1黄和MESSAGE1总线的数据是.color1两个副本:黄.message1:总线

So if I push color1 "RED" and message1 "Rover".. the data is correct then if I push color1"yellow" and message1 "Bus" the data is two copies of .color1:"yellow" .message1:"Bus"

推荐答案

当你按下 SERVERMESSAGE servermessagelist 你简直太推到该对象的引用(或多或少)。因此,要 SERVERMESSAGE 所做的任何更改都处处体现你必须对它的引用。这听起来像你想要做的是推对象的克隆到列表中。

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.

声明函数如下:

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) );

这篇关于JavaScript的对象推到数组改变整个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆