Javascript将对象推入数组会更改整个数组 [英] Javascript pushing objects into array changes entire array

查看:37
本文介绍了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.

因此,如果我推送 color1 "RED" 和 message1 "Rover".. 数据是正确的,那么如果我推送color1"yellow" 和 message1 "Bus" 数据是 .color1:"yellow" .message1:"Bus" 的两个副本

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天全站免登陆