简体   繁体   中英

Javascript Object Array access properties undefined?

Here is some output that I get from firebug

<div id='div_undefined'>[{"Region":"AD","Date":"","ArticleID":"abc-345"},    {"Region":"CD","Date":"","ArticleID":"abc-345"}]</div>

You can see the JS Object array in there and notice the div_undefined. If you look at the funciton below I know that my object is defined because it is printing out. Why would Items[0] return undefined when I try to access ArticleID

here is the code from my function

function myFunc(Items){
    var item = Items[0];
    Write("<div id='div_" + item.ArticleID + "'>" + Items + "</div>");
}

If concatenating Items produces this output, then it's a string (containing JSON) and you have to parse it to a JS data structure first (an array in this case):

function myFunc(Items){
    Items = JSON.parse(Items);
    var item = Items[0];
    Write("<div id='div_" + item.ArticleID + "'>" + Items + "</div>");
    // Will output
    // <div id='div_abc-345'>[object Object], [object Object]</div>
}

Ideally you would do this before you pass the value to the function. I don't know which output you are after, so that's all I can advice.


Otherwise, Items[0] refers to the first letter of the string (a string as well) and strings don't have an ArticleID property, hence you get undefined .


You might find this question helpful as well: Access / process (nested) objects, arrays or JSON And as mentioned by Matt (and in the other question), if you want to debug your code, use console.log .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM