在node.js和socket.io中发送数组时的错误
我使用 socket.io 版本 0.8.4
我已将问题归结为以下内容。我的数据如下所示:
data.prop1 = [];
data.prop1.push("man");
data.prop2 = [];
data.prop2["hey"] = "man";
我以这种方式将数据从服务器发送到客户端:
socket.emit("data", data);
在客户端,我以这种方式接收数据:
socket.on("data", function(data){ console.log(data); });
奇怪的是:
data.prop1 = [];
data.prop1.push("man"); // This data exists in the client side data object
data.prop2 = [];
data.prop2["hey"] = "man"; // This data does not exist.
data.prop2 在客户端只是一个空数组。
prop2 中表单上的 json 序列化数组是否存在已知错误?
提前谢谢
您编辑:
使用此解决方法解决了问题:
data.prop1 = [];
data.prop1.push("man");
data.prop2 = {}; // <= Object instead of array
data.prop2["hey"] = "man";
I use socket.io version 0.8.4
I have boiled down my problem to the following. I have data looking like this:
data.prop1 = [];
data.prop1.push("man");
data.prop2 = [];
data.prop2["hey"] = "man";
I send the data from the server to the client this way:
socket.emit("data", data);
On the client side I receive the data this way:
socket.on("data", function(data){ console.log(data); });
The weird thing is:
data.prop1 = [];
data.prop1.push("man"); // This data exists in the client side data object
data.prop2 = [];
data.prop2["hey"] = "man"; // This data does not exist.
data.prop2 is just an empty array on the client side.
Is there a known bug in json serializing arrays on the form in prop2?
Thankyou in advance
EDIT:
Problem solved using this workaround:
data.prop1 = [];
data.prop1.push("man");
data.prop2 = {}; // <= Object instead of array
data.prop2["hey"] = "man";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
关于
JSON.stringify
的 ECMA-262:数组应该有数字属性名称。因此,当
data.prop2
转换为JSON(我想socket.io发送数据)时,它不会获得'hey'
属性。如果你想使用非数字属性名称,你应该使用对象而不是数组:ECMA-262 about
JSON.stringify
:Arrays are supposed to have numerical property names. So when the
data.prop2
is transformed to JSON (which socket.io sends the data in, I imagine), it doesn't get the'hey'
property. If you want to use non-numerical property names, you should use objects instead of arrays:不幸的是,Javascript 并不是这样工作的。
查看这篇文章,大约一半。它解释了您尝试设置 data.prop2["hey"] = "man"; 的问题
Unfortunately, Javascript doesn't really work like that.
Check out this article, about half way down. It explains the problem where you try to set data.prop2["hey"] = "man";