Javascript在控制台上不应该定义数据

gaf*_*ill 0 javascript

我有这些数据:

{
   "id":"01",
   "new":0,
   "closed":0,
   "locked":0,
   "subhere":[
      {
         "id":"123",
         "subname":"somename"
      }
Run Code Online (Sandbox Code Playgroud)

...等等...

在控制台日志中,我要显示它(请参阅注释):

console.log('Level 1 ID: ' + obj.id); //This works!
console.log('Level 1 Closed ' + obj.closed); //This works!
console.log('Level 1 Locked ' + obj.locked); //This works!
console.log('Level 2 Subhere ID ' + obj.subhere.id); //This returns Undefined!
Run Code Online (Sandbox Code Playgroud)

最后一个console.log给了我Undefined但是我没看到问题是什么...为什么?

关于为什么我在最后一个上获得Undefined的任何想法?

Osk*_*ura 6

subhere 是一个数组 - 你将它称为一个对象.

因此它应该是:

console.log(obj.subhere[0].id); 
Run Code Online (Sandbox Code Playgroud)


Pra*_*lan 5

由于obj.subhere是一个数组所以obj.subhere.idundefined.首先需要获取数组元素作为对象.

console.log('Level 2 Subhere ID ' + obj.subhere[0].id)
//---------------------------------------------^^^----
Run Code Online (Sandbox Code Playgroud)

var obj = {
  "id": "01",
  "new": 0,
  "closed": 0,
  "locked": 0,
  "subhere": [{
    "id": "123",
    "subname": "somename"
  }]
};

console.log('Level 2 Subhere ID ' + obj.subhere[0].id)
Run Code Online (Sandbox Code Playgroud)