Object
2021. 5. 18. 17:17ㆍTIL/자바스크립트
728x90
object = {key : value};
1. Literals and properties
const ojb1 = {}; //'object literal' syntax
const obj2 = new Object(); // 'object constructior' syntax
function print(person) {
console.log(person.name);
console.log(person.age);
}
const bella = { name: 'bella', age: 4};
print(bella);
// with JavaScript magic (dynamically typed language)
// can add properties later
bella.hasJob = true;
console.log(bella.hasJob);
// can delete properties later
delete bella.hasJob;
console.log(bella.hasJob);
2. Computed properties
Key should be always string
console.log(bella.name); // 코딩하는 순간 값을 받아오고 싶을 때
console.log(bella['name']); //runtime에서 값이 정해질때
bella['hasJob'] = true; //실시간으로 값을 받아오고 싶을 때
console.log(bella.hasJob);
function printValue(obj, key) {
console.log(obj[key]);
}
printValue(bella, 'name');
printValue(bella, 'age');
3. Property value shorthand
const person1 = { name: 'bob', age: 2};
const person2 = { name: 'steve', age: 3};
const person3 = { name: 'dave', age: 4};
const person4 = new Person('bella', 30);
console.log(person4);
4. Constructior function
function Person(name, age) {
// this = {};
this.name = name;
this.age = age;
// return this;
};
5. in poerator: property existence check (key in obj)
console.log('name' in bella); //true
console.log('age' in bella); //true
console.log('random' in bella); //false
console.log(bella.random); //undefined
6. for..in vs for..of
for (key in obj)
console.clear();
for (let key in bella) {
console.log(key);
}
// for (value of iterable)
const array = [1, 2, 4, 5];
// for (let i = 0; i < array.length; i++) {
// console.log(array[i]);
// }
for (let value of array) {
console.log(value);
}
7. Fun cloning
Object.assign(dest, [obj1, obj2, obj3...])
const user = { name: 'bella', age: '20' };
const user2 = user; //동일한 레퍼런스를 갖게 됨
user2.name = 'coder';
console.log(user); //coder
// old way
const user3 = {};
for (let key in user) {
user3[key] = user[key];
}
console.clear();
console.log(user3);
//
const user4 = Object.assign({}, user);
console.log(user4);
// another example
const fruit1 = { color: 'red' };
const fruit2 = { color: 'blue', size: 'big' };
const mixed = Object.assign({}, fruit1, fruit2); //동일한 값을 갖고 있다면 뒤에 있는 값으로 덮어씌워짐
console.log(mixed.color); // blue
console.log(mixed.size); // big
'TIL > 자바스크립트' 카테고리의 다른 글
Array API Quiz (0) | 2021.05.20 |
---|---|
Array 배열 (0) | 2021.05.18 |
class object 객체지향 (0) | 2021.05.17 |
Function 함수 (0) | 2021.05.14 |
자바스크립트 연산자, if문 for문 switch문 (0) | 2021.05.13 |