gpt4 book ai didi

node.js - Node for循环无意中改变了对象

转载 作者:太空宇宙 更新时间:2023-11-04 00:36:05 24 4
gpt4 key购买 nike

我有一个 Angular 应用程序,它与 Node.js 套接字服务器通信,而 Node.js 套接字服务器又与 Node.js 应用程序服务器通信。在此套接字服务器功能中,我想根据哪个用户来清除应用程序服务器的响应。我制作了要擦洗的对象手的副本“emitHand”,并将该副本发送给客户端。看起来副本正在影响原始对象,因为循环在第一个对象之后停止,并且其他客户端没有收到消息。

第一个控制台输出显示第二个客户端已连接,并且在数据操作之前位于clientsSockets 列表中。所以我应该只会看到“用户未连接”4 次。

第二个控制台输出显示原始对象 hand.players 在从未被调用时正在更改。这是我的问题。为什么代码中只有emitHand.players 发生变化时hand.players 也会发生变化?我也尝试了 forEach(注释掉) 无济于事。

socket.on('hand', function(receivedHand) {  
console.log('clientSockets[56fde5327ee729ac1a37fd1c].userId '+ util.inspect( clientSockets['56fde5327ee729ac1a37fd1c'].userId, false, null));
var hand = null;
PostHand(receivedHand).then(function(data) {
hand = JSON.parse(data);
console.log('hand.players'+util.inspect(hand.players, false,null));
var emitHand=hand;
// emitHand.players.forEach(function(player, index, handPlayers) {
for(var index in emitHand.players){var player=emitHand.players[index];
if (clientSockets[player.userId]!=null){
ScrubHand(emitHand.players,index).then(function(data) {
emitHand.players=data.emitHandPlayers;
clientSockets[data.emitHandPlayers[data.index].userId].socket.emit('hand', emitHand);
console.log('hand.players'+util.inspect(hand.players, false,null));
});
}else{
console.log('user not connected'+player.userId);
}
}
// });
});
});

这是输出。

clientSockets[56fde5327ee729ac1a37fd1c].userId '56fde5327ee729ac1a37fd1c'
hand.players[ { userId: '56ccbc3992d91b401b62f850',
seat: 1 },
{ userId: '56ccbc9c92d91b401b62f857',
seat: 2 },
{ userId: '56fde4ec2ecc97901f232f65',
seat: 3 },
{ userId: '56fde5327ee729ac1a37fd1c',
seat: 4 },
{ userId: '56fdef1347636f50171c5026',
seat: 5 },
{ userId: '5720f4d718e3775020bdaf17',
seat: 6 } ]
user not connectednull
user not connectednull
user not connectednull
user not connectednull
user not connectednull
hand.players[ { userId: '56ccbc3992d91b401b62f850',
seat: 1},
{ userId: null,
seat: 2},
{ userId: null,
seat: 3},
{ userId: null,
seat: 4},
{ userId: null,
seat: 5},
{ userId: null,
seat: 6} ]

最佳答案

这是因为hands和emitHand是同一个对象。在 Javascript 中,所有对象都是通过引用调用的。因此,当您 var emmitHand=hand; 时,您只会获得对同一对象的另一个引用。

如果您想要硬拷贝,则需要克隆该对象:

var emitHand = JSON.parse(JSON.stringify(hand));

您可能想看看:

What is the most efficient way to deep clone an object in JavaScript?

关于node.js - Node for循环无意中改变了对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38944987/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com