简体   繁体   中英

Trying to access array object in JS gives me undefined

I have this JS output

在此处输入图片说明

I'm trying to access the first member of the ModelState array using this approach:

console.log(data.ModelState[0]);

But I'm getting undefined error.

Also when trying to do alert(data.ModelState) I'm getting Object object.

How can I access the first value in the ModelState array?

You would have to access it using data.ModelState[''][0] . It seems you have a nested array, with the element of the array containing the two strings has an empty or whitespace-only string for an index.

[object Object] is your first clue there—although I can't reproduce your exact problem, it looks like the object you think is an array is actually a JavaScript Object , which is a different data structure. JS Objects are fairly similar to objects from other object oriented languages. Their string representation is, as you've noticed, [object Object]] , regardless of their contents.

> String({})
< "[object Object]"
> String({abc: "foo", def: "bar"})
< "[object Object]"

If you update your question with steps on how to reproduce it, I can help more, but I hope that's enough to get you on the right track!

I appears that your data contains an array which has a blank or whitespace key. So it most likely looks like this

{
    ModelState: {
        "": [ "string1", "string2" ]
    }
}

You would need to access it via the key there, as long as you know what it is, for example data.ModelState[""][1] //"string1"

There are also alternatives if you are not sure what they key would be or want a less brittle code:

 var data = { ModelState: { "": [ "string1", "string2" ] } }; console.log("--Using Object.keys--") Object.keys(data.ModelState).forEach(function(key) { console.log(data.ModelState[key]); }) console.log("--Using for...in loop--") for (var key in data.ModelState) { console.log(data.ModelState[key]); }

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