【问题标题】:Bug when sending array in node.js and socket.io在 node.js 和 socket.io 中发送数组时出现错误
【发布时间】:2012-02-10 12:38:09
【问题描述】:

我使用的是 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序列化数组有已知bug吗?

提前谢谢你

编辑:

使用此解决方法解决了问题:

data.prop1 = [];
data.prop1.push("man");
data.prop2 = {}; // <= Object instead of array
data.prop2["hey"] = "man";

【问题讨论】:

    标签: arrays serialization node.js socket.io


    【解决方案1】:

    ECMA-262 关于JSON.stringify:

    数组的表示只包括介于零和array.length – 1 之间的元素。命名属性从字符串化中排除。

    数组应该具有数字属性名称。因此,当 data.prop2 转换为 JSON(我想是 socket.io 将数据发送到其中)时,它不会获得 'hey' 属性。如果你想使用非数字属性名,你应该使用对象而不是数组:

    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"
    

    【讨论】:

      【解决方案2】:

      不幸的是,Javascript 并不是这样工作的。

      查看this article,大约一半。它解释了您尝试设置 data.prop2["hey"] = "man";

      【讨论】:

        猜你喜欢
        • 2015-06-24
        • 2021-04-22
        • 1970-01-01
        • 2015-04-23
        • 2013-01-19
        • 1970-01-01
        • 2017-09-22
        • 2016-05-14
        • 1970-01-01
        相关资源
        最近更新 更多