Reference Nested JavaScript Object

2019-04-11 08:44发布

I have this code:

var string = { 
            nameString : "nameValue",
            nameString2 : "nameValue2",
            nameString3 : "nameValue3",
            datathing : 0,
        };

var data = { 
            data : 1,
            dataNum2 : 2,
            dataNum3 : 3,
            dataNum4 : 4,
        };

var thing = { 
            datathing1 : 10,
            datathing2 : 20,
            datathing3 : 30,
            datathing4 : 40,
        };

var object = { 
            object1 : string,
            data1 : data,
            thing1 : thing,
        };

Why do neither of these means to access the data work:

alert("testReference= " + object['object1']['string']['nameString']);
alert("testReference= " + object.object1.string.nameString);

I cannot understand it, even though similar examples found below and textbooks state explicitly that they should work:

Accessing nested JavaScript objects with string key

Thanks in advance for any input!

I am currently constructing an object and passing it around, a 'for in' will bring up the values but a 'typeof' test or any other way I try and access will not work, either I will encounter an error (which breaks the program, I think) or I get 'undefined'....

One last thing if this gets solved, is it ok to nest a key that is the same name value as its parent, such as data.data - this leads to the possibility of further nesting such as data.data.data...

1条回答
SAY GOODBYE
2楼-- · 2019-04-11 09:27

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!

查看更多
登录 后发表回答