Bug when sending array in node.js and socket.io

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";

ECMA-262 about JSON.stringify
:

The representation of arrays includes only the elements between zero and array.length – 1
inclusive. Named properties are excluded from the stringification.

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"
Hello, buddy!稿源:Hello, buddy! (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Bug when sending array in node&period;js and socket&period;io

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录