在node.js和socket.io中发送数组时的错误 [英] Bug when sending array in node.js and socket.io
问题描述
我使用的是socket.io版本0.8.4
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); });
奇怪的是:
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只是客户端上的一个空数组.
data.prop2 is just an empty array on the client side.
prop2中的表单上的json序列化数组中是否存在已知错误?
Is there a known bug in json serializing arrays on the form in prop2?
先谢谢您
使用以下变通办法解决了问题:
Problem solved using this workaround:
data.prop1 = [];
data.prop1.push("man");
data.prop2 = {}; // <= Object instead of array
data.prop2["hey"] = "man";
推荐答案
关于JSON.stringify
的ECMA-262:
ECMA-262 about JSON.stringify
:
数组的表示形式仅包括介于零和
array.length – 1
(含)之间的元素.命名属性被排除在字符串化之外.
The representation of arrays includes only the elements between zero and
array.length – 1
inclusive. Named properties are excluded from the stringification.
数组应该具有数字属性名称.因此,当data.prop2
转换为JSON(我想是socket.io将数据发送到其中)时,它没有获得'hey'
属性.如果要使用非数字属性名称,则应使用对象而不是数组:
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:
data.prop1 = [];
data.prop1.push("man");
data.prop2 = {}; // Notice we're creating an object, not an array.
data.prop2["hey"] = "man"; // Alternatively: data.prop2.hey = "man"
这篇关于在node.js和socket.io中发送数组时的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!