An object is very similar to an array but with the difference that you define the keys yourself. You're not limited to using only numeric indexes but can use friendlier keys, such as first_name, age, and so on.
Let's take a look at a simple object and examine its parts:
var hero = {
breed: 'Turtle',
occupation: 'Ninja'
};
You can see that:
The name of the variable that contains the object is hero
Instead of [ and ] which you use to define an array, you use { and }
for objects
You separate the elements (called properties) contained in the object
with commas
The key/value pairs are divided by colons, as key: value
The keys (names of the properties) can optionally be placed in quotation marks.
For example these are all the same:
var o = {prop: 1};
var o = {"prop": 1};
var o = {'prop': 1};
It's recommended that you don't quote the names of the properties (it is also less typing!), but there are some cases when you have must use quotes:
If the property name is one of the reserved words in JavaScript (see Appendix A)
If it contains spaces or special characters (anything other than letters, numbers, and the underscore character)
If it starts with a number
Accessing Object's Properties
There are two ways to access a property of an object:
Using square bracket notation, for example hero['occupation']
Using the dot notation, for example hero.occupation
属性也可能是函数
本文介绍了JavaScript中对象的概念,对比了对象与数组的区别,并详细解释了如何使用两种方式(方括号和点符号)来访问对象的属性。此外,还讨论了在定义对象属性时何时需要使用引号。
283

被折叠的 条评论
为什么被折叠?



