객체(Object) 사용법

1. Property value shorthand / Constructor function

// 3. Property value shorthand
const person1 = {name : 'aa', age : 2};
const person2 = new Person('bb',11);

console.log(person1); //  {name: "aa", age: 2}
console.log(person2); //  Person {name: "bb", age: 11}


// 4. Constructor function
function Person(name, age) {
    this.name = name;
    this.age = age;

}

 

2. key 값이 있는지 체크 (in operator: property existence check (key in obj)

console.log('name' in ellie); // true
console.log('aaa' in ellie); // false

for..in vs for..of

for(let key in ellie){
    console.log(key);
}

let arry = [1,2,3,4,5];
for(let value of arry) {
    console.log(value);
}

 

3. 객체 복사

  • Object.assign 함수를 통해 간편하게 복사할 수 있다.
const user = {name : 'kyh', age : 20};
const user2 = {};

console.log(user);

Object.assign(user2, user); // user를 user2로 복사

예제

const fruit1 = { color : 'red'};
const fruit2 = { color : 'blue', size : 'big'};
const mixed = Object.assign({}, fruit1, fruit2); // 나중(뒤)의 값이 덮어 씌워져서 blue로 저장된다.
console.log(mixed); // {color: "blue", size: "big"}

댓글

Designed by JB FACTORY