let person = {
name: 'Eric',
age: 20,
'Favorite Movie': 'The Godfather',
family: ['Father', 'Mother', 'Brother']
};
person.name; // Returns 'Eric'
person.family;
// Returns ['Father', 'Mother', 'Brother']
['Father', 'Mother', 'Brother'][0]
//Return 'Father'
person.address; // Return undefined
objectname.propertyname = value;
person.name = 'Teddy'
const persion = {age: 20};
person = {type: '22'};
//Return TypeError, const 변수에는 재할당 할 수 없기 때문
person.age = 22;
//Return 22, property 재할당은 가능
person.country = 'Korea';
//Create new property, property 추가됨
delete person.country;
//Remove country property, delete 사용 시 property 삭제 가능
//anonymous function expression
const person = {
motto: function () {
console.log('No gain No pain');
}
};
//new method syntax(ES6)
const person = {
motto () {
console.log('No gain No pain');
}
};
person.motto();
//Prints 'No gain No pain'
const person = {
name: 'Teddy',
age: 20,
friends: {
school: {
name: 'mory',
age: 20,
'Favorite color' : ['black', 'white']
},
'Mid-Gym': {
name: 'Hans',
age: 29
}
}
};
person.frinds['Mid-Gym'].name;
//Return 'Hans'
const yellow = person.friends.school['Favorite color'][0]
// Return 'Favorite color' : ['yellow', 'black', 'white']
...
'Mid-Gym': [{
name: 'Hans'
age: 29
}] // Array
...
Objects are passed by reference.
설명 참조:
Loops are programming tools that repeat a block of code until a condition is met.
We learned how to iterate through arrays using their numerical indexing, but the key-value pairs in objects aren’t ordered !
JavaScript has given us alternative solution for iterating through objects with the for...in syntax .
for...in will execute a given block of code for each property in an object.
const person = {
name: 'Teddy',
age: 20,
friends: {
school: {
name: 'mory',
age: 20,
'Favorite color' : ['black', 'white']
},
'Mid-Gym': {
name: 'Hans',
age: 29
}
}
};
//for...in
for (let place in person.friends) {
console.log(`${place}: ${person.friends[place].name}`)};
출처 codeacademy javascript object