JavaScript数组克隆 [英] JavaScript array cloning

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

问题描述

我有这种方法来制作一个数组

I have this way to make an array

var playerList = [];

exports.player = function(socket, name)
{
    this.id = socket.id;
    this.name = name;
    this.x = 20;
    this.y = 40;

    return this
}

exports.addPlayer = function(data)
{
    playerList.push(data)
}

我正在像这样向 playerList 数组中添加项目

And I'm adding items to playerList array like this

var client = new player(socket, data);
exports.addPlayer(client);

但是我也有一个可以进行以下操作的函数

But I also got a function that makes the following

exports.getSafeList = function(id)
{
    var player_array = playerList.slice();

    for(var i = 0; i < player_array.length; i++)
    {
        if(player_array[i].id != id)
        {
            player_array[i].id = 'unknown';
        }
    }

    return player_array;
}

现在我要执行以下操作

exports.getPlayerList = function()
{
    return playerList;
}

console.log(players.getPlayerList())
console.log(players.getSafeList(id))

到目前为止,代码运行良好,但是当我登录这两个函数时,似乎 getPlayerList 变量与 player_list 合并,这就是输出

So far the code is working fine but when I log the 2 functions it seems that getPlayerList variable merges with player_list one, this is the output

当阵列上只有一个播放器时

When theres just ONE player on the array

[ { id: 'tjvh8XdMtX-o6QYDAAAB', name: 'Raggaer', x: 20, y: 40 } ]

[ { id: 'tjvh8XdMtX-o6QYDAAAB', name: 'Raggaer', x: 20, y: 40 } ]

但是当有更多的时候:

[ { id: 'unknown', name: 'Raggaer', x: 20, y: 40 },
  { id: '2-K5At07wLV4BDiAAAAC', name: 'Alvaro', x: 20, y: 40 } ]

[ { id: 'unknown', name: 'Alvaro', x: 20, y: 40 },
  { id: '2-K5At07wLV4BDiAAAAC', name: 'Alvaro', x: 20, y: 40 } ]

您可以在两个数组上看到 id 不应显示为未知",因为我没有修改 playerList 数组...

As you can see on both arrays id appears as "unknown" when it shouldn't, since I'm not modyfing the playerList array...

推荐答案

问题在于,当

The problem is that while Array.prototype.slice() will create a separate copy of the original array, its items will still be references to the same object instances. So modifying an item in one array ends up modifying the corresponding item in the cloned array.

如果您的项目是简单的数据对象(没有功能),则此解决方法可能会帮您解决问题:

If your items are simple data objects (no functions), this workaround might do the trick for you:

// instead of "var player_array = playerList.slice();"
var player_array = JSON.parse(JSON.stringify(playerList));

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

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