objects are not ordered.
Instead of identifying elements by index, we identify them by key. So an object is a list of key / value pairs separated by colon (:).
var employee = {
'name': 'James Taylor',
'yearOfBirth': 1948,
'ID': 'SBJ0001',
'role': 'IT Analyst'
};
Objects keys are also called properties(屬性)
To access the properties we can use braces or the dot notation:
console.log( employee['ID'] ); // The console will show 'SBJ0001'
console.log( employee.ID ); // Same thing using the dot notation
Important: the dot notation only works with properties that follow the variables naming rules.
var test = {
'property1': 'Some value',
'2a': 'Some other value',
09335: 'Another value',
'hello-world': 'Last value'
};
// 'property1' can be retrieve恢復 using the dot notation:
console.log( test.property1 ); // The console will show 'Some value'
// The other ones can't because they don't follow the naming rules. They can only be retrieved with braces.
console.log( test['hello-world'] ); // The console will show 'Last value'
var employee = {
'name': 'James Taylor',
'yearOfBirth': 1948,
'ID': 'SBJ0001',
'role': 'IT Analyst'
};
employee.role = 'IT Manager'; // alter a value
employee.passport = 'KV09888'; // add a new property
console.log(employee);
/* The console will show:
{
'name': 'James Taylor',
'yearOfBirth': 1948,
'ID': 'SBJ0001',
'role': 'IT Manager',
'passport': 'KV09888'
};
*/
Some other 方向 worth remembering:
Therefore we can conclude the following: