下面我有以下代码:
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"}}
这是怎么回事?!?!?
前三个警报(显示 imageType
、uploadReason
和 fileKey
分配)符合预期,但 iVO
code> 对象的行为根本不像我预期的那样。 JSON.stringify
方法是正常的 json2.js
方法,我没有修改它。
为什么“新赛季”显示为每个 iVO["images"]
字段值?为什么没有 iVO
分配好好工作?!? 我需要做什么来修复它们?
JSON.stringify(iVO)
的所需输出将是(以 pretty-print 形式):
{
"images":
{
"b2fc":
{
"imageType":"BoxArt",
"uploadReason":"New season",
"fileKey":"b2fc"
}
}
}
提前致谢!
最佳答案
当然,你定义的位置
iVO["images"][thisImage.fileKey] = thisImage;
iVO["images"][thisImage.imageType] = imageType;
iVO["images"][thisImage.uploadReason] = uploadReason;
thisImage
是之前分配给 fileKey
的字符串,因此 thisImage.fileKey
、thisImage.imageType
和 thisImage.uploadReason
是无效引用
可能你想做一些类似的事情 iVO["images"][fileKey]["imageType"] = imageType
关于javascript - 为什么 Javascript 对象不更新字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10293365/