开发者

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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜