我有这个JSON字符串:
{
"attachedFiles": [{
"link": "/site.com/dir?id=12993&SESSION=40af90dd-c1f3-4678-93e5-a4b36f3597b0&SESSIONTICKET=SESS:67bf209be2",
"fileName": "file1.txt",
"docDate": "24.02.2014",
"docTime": "13:54",
"docId": "12993"
}],
"requestId": 48,
"tasksId": 0,
"workId": 10558
}
Run Code Online (Sandbox Code Playgroud)
我正在转换它:
var resdata = xhr.responseText; // the string response from the server
var resObj = JSON.parse(resdata);
Run Code Online (Sandbox Code Playgroud)
然后我试图通过下面的代码访问(打印值)对象fileName内部attachedFiles:
console.log(resObj.attachedFiles.fileName);
Run Code Online (Sandbox Code Playgroud)
它总是回归undefined.我知道我在这里捏着一些很小的东西,但是我无法发现它.
attachedFiles是数组.因此,尝试使用索引器访问数组内容
resObj.attachedFiles[0].fileName // 0th index, 1st Element
Run Code Online (Sandbox Code Playgroud)
访问数组中的所有元素.感谢@Cerbus评论
for(var i = 0, l = resObj.attachedFiles.length; i < l;i++)
{
console.log(resObj.attachedFiles[i].fileName);
}
Run Code Online (Sandbox Code Playgroud)