2012-04-24 55 views
0

下面我有以下代碼:爲什麼Javascript對象不更新字段?

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

這到底是怎麼回事?!?!?

前三個警報(表示imageTypeuploadReason,和fileKey分配)如預期,但iVO對象不作用於所有像我的預期。 JSON.stringify方法是正常的json2.js方法,我沒有修改它。

爲什麼「新季節」顯示每iVO["images"]字段值?爲什麼iVO作業不能正常工作?!? 我需要做些什麼來修復它們?

JSON.stringify(iVO)所需的輸出是(在漂亮地打印表格):

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

提前感謝!

回答

1

肯定的,在那裏你定義

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

thisImage是一個字符串,由以前分配給fileKey所以thisImage.fileKeythisImage.imageTypethisImage.uploadReason是無效引用

可能是你想要做這樣的事情iVO["images"][fileKey]["imageType"] = imageType

1

我想你想

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

,我會寫爲

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

有沒有神奇的自動unnesting子對象/ vivification與在他們點字段名。