循环节点无意中改变了对象

我有一个angular度的应用程序,谈到一个node.js套接字服务器,谈话node.js应用服务器。 在这个套接字服务器函数中,我想根据哪个用户来清理应用服务器的响应。 我把一个拷贝放到了被擦净的物体的手上,然后把这个拷贝发送给客户端。 它看起来像副本影响的原始对象,因为循环停止后,第一个和其他客户端没有得到消息。

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

第二个控制台输出显示原始对象hand.players在从未调用时正在更改。 这是我的问题。 为什么hand.players只有当emitHand.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} ] 

这是因为双手和放手是同一个对象。 在Javascript中,所有对象都通过引用来调用。 所以当你var emitHand=hand; ,你只是得到另一个对同一个对象的引用。

如果你想要一个硬拷贝,你需要克隆这个对象:

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

你可能想看看:

什么是在JavaScript中深入克隆对象的最有效方法?