[英]Trying to access array object in JS gives me undefined
I have this JS output我有这个 JS 输出
I'm trying to access the first member of the ModelState array using this approach:我正在尝试使用这种方法访问 ModelState 数组的第一个成员:
console.log(data.ModelState[0]);
But I'm getting undefined error.但我收到未定义的错误。
Also when trying to do alert(data.ModelState) I'm getting Object object.同样在尝试执行 alert(data.ModelState) 时,我正在获取 Object 对象。
How can I access the first value in the ModelState array?如何访问 ModelState 数组中的第一个值?
You would have to access it using data.ModelState[''][0]
.您必须使用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. [object Object]
是你的第一个线索——虽然我无法重现你的确切问题,但看起来你认为是数组的对象实际上是一个JavaScript Object ,它是一种不同的数据结构。 JS Objects are fairly similar to objects from other object oriented languages. JS 对象与其他面向对象语言的对象非常相似。 Their string representation is, as you've noticed, [object Object]]
, regardless of their contents.正如您所注意到的,它们的字符串表示是[object Object]]
,而不管它们的内容如何。
> 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"
您需要通过那里的密钥访问它,只要您知道它是什么,例如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]); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.