Reference Nested JavaScript Object

本小妞迷上赌 提交于 2019-12-04 11:54:36

Let's look at what's wrong with each example, then take a look at the way that works right.

Example 1

object['object1']['string']['nameString']

  1. We expect object['object1'] to return the object string, right? So lets simplify the big expression by replacing that part of it. That'll make it easier for us to understand.

  2. So now we have string['string']['nameString'].

  3. But string has no member called 'string', so string['string'] returns undefined.

  4. And when you try to treat undefined as an object, you get an error!

Example 2

object.object1.string.nameString

  1. We expect object.object1 returns the object string, right? So lets simplify the big expression by replacing that part of it. That'll make it easier for us to understand.

  2. So now we have string.string.nameString.

  3. But string has no member called 'string', so string.string returns undefined.

  4. And when you try to treat undefined as an object, you get an error!.

What You Want

object.object1.nameString (or object['object1']['nameString'])

  1. We expect object.object1 returns the object string, right? So lets simplify the big expression by replacing that part of it. That'll make it easier for us to understand.

  2. So now we have string.nameString, and we expect that to return "nameValue".

  3. And it does!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!