简体   繁体   中英

What's the difference in this code (JS)?

I'm wondering what's the difference between this code:

var c = [{"test": 1}];

and this code

var c = {"test": 1};

Firebug says both of them are objects but if you do console.log(c.test) with the first example it'll return "undefined". So I'm kind of wondering what's that all about and how should the first example be accessed?

The first is an array containing one element which is the {"test": 1} object while the second is the {"test": 1} object itself.

So with the first you could c[0].test while with the second you could c.test .

The first c is an Array containing an Object, the second an Object.

In JavaScript everything is an Object, so that's why Firebug says they are both objects. To get the test property from the first c, you have to reference the first element of the Array (being the actual Object), so c[0].test would return 1. If you need to know if c is (instance of) an Array, try typing c instanceof Array in the Firebug console and run it (returns true ). To verify that an Array is also an Object do the same for c instanceof Object (returns true ).

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