0

下面我有以下代码:

var imageType = "BoxArt";
var uploadReason = "New season";
var fileKey = "b2fc";

alert("imageType = " + imageType);
alert("uploadReason = " + uploadReason);
alert("fileKey = " + fileKey);

var iVO = { "images":{}};
var thisImage = fileKey;
iVO["images"][thisImage.fileKey] = thisImage;
iVO["images"][thisImage.imageType] = imageType;
iVO["images"][thisImage.uploadReason] = uploadReason;

alert("iVO['images'][thisImage.imageType] = " + iVO["images"][thisImage.imageType]);
alert("iVO['images'][thisImage.uploadReason] = " + iVO["images"]    [thisImage.uploadReason]);
alert("iVO['images'][thisImage.fileKey] = " + iVO["images"][thisImage.fileKey]);
alert("JSON.stringify(iVO):\n" + JSON.stringify(iVO));

当我执行此操作时,我得到以下输出:

imageType = "BoxArt"
uploadReason = "New season"
fileKey = "b2fc"
iVO['images'][thisImage.imageType] = "New season"
iVO['images'][thisImage.uploadReason] = "New season"
iVO['images'][thisImage.fileKey] = "New season"
JSON.stringify(iVO):
{"images"}:{"undefined":"New season"}}

这里发生了什么?!?!?

前三个警报(显示imageTypeuploadReasonfileKey分配)与预期的一样,但iVO对象的行为完全不像我预期的那样。该JSON.stringify方法是正常的json2.js方法,我没有修改它。

为什么“新赛季”显示为每个iVO["images"]字段值?为什么iVO作业不能正常工作?!?我需要做什么来修复它们?

所需的输出JSON.stringify(iVO)将是(以漂亮的打印形式):

{
    "images":
    {
        "b2fc":
        {
            "imageType":"BoxArt",
            "uploadReason":"New season",
            "fileKey":"b2fc"
        }
    }
}

提前致谢!

4

2 回答 2

1

我想你想要

iVO['images'][thisImage] = {
         "imageType":"BoxArt",
        "uploadReason":"New season",
        "fileKey":"b2fc"
    };

我会写成

 iVO.images[thisImage] = {
         "imageType":"BoxArt",
        "uploadReason":"New season",
        "fileKey":"b2fc"
    };

对于带有点的字段名称,没有神奇的自动取消嵌套/激活子对象。

于 2012-04-24T07:20:04.680 回答
1

当然,你定义的地方

iVO["images"][thisImage.fileKey] = thisImage;
iVO["images"][thisImage.imageType] = imageType;
iVO["images"][thisImage.uploadReason] = uploadReason;

thisImage是先前分配给fileKeyso的字符串thisImage.fileKeythisImage.imageType并且thisImage.uploadReason是无效引用

可能你想做类似的事情iVO["images"][fileKey]["imageType"] = imageType

于 2012-04-24T07:22:19.433 回答