const { id, name, addr = 'Seoul' } = { id: 1, name: 'Hong', add: 'Pusan' };
const id = 1;
const name = 'Hong';
const addr = 'Seoul';
Swap이 이렇게 가능하다.
Swapping할 때, 스택에 있는 메모리 주소를 할당하기 때문에 새로운 주소값이 생성되게 되고,
변수는 모두 immutable이기 때문에 새로운 주소를 할당하게 된다.
나중에 boolean이 들어갈 수도 있고, String이 들어갈 수 있기 때문에 그렇다.
[a, b] = [b, a]; //let t = a; a = b; b = t;
Class Destructuring
lass A {
constructor(a,b) {
this.a = a;
this.b = b
}
// ...
}
const x = new A(1, 2);
const {a, b} = x;
new A(1,2) 는 객체를 return 한다.
const { id, name = 'Hong', addr = 'xx' } = { id: 1, name: undefined, addr: null };
name은 undefined가 아닌 'Hong'이 할당 됨,
null은 그대로 null
undefined이 왔을 때만 초기 값으로 설정한다. -> 없는거랑 똑같음
const obj = {i: 1, j: 2, l: 3, m: 4, n: 5};
let { j, i, k = i * j * n } = obj;
n은 변수 테이블에 없기 때문에 nan이 된다.
Spread operator
const user2 = {...user, name: '홍길동'}
이건 깊은 복사
const user2 = user일 경우 shallow copy이다.
들어오는 변수 이름이 같다면 생략해도 된다.
function f1({ id, name }) {
console.log(id, name);
}
function f1({ id:id, name:name }) {
console.log(id, name);
}
passwd 뺀 나머지 값 받기
const user = { id: 1, name: "Hong", passwd: "xxx", addr: "Seoul" };
const { passwd, ...userInfo } = user;
console.log(userInfo);
//print: {id: 1, name: 'Hong', addr: 'Seoul'}
구조만 맞춰주면 된다.
const arr = [[{ id: 1 }], [{ id: 2 }, { id: 3 }]];
const [[{ id: id1 }], [{ id: id2 }, { id: id3 }]] = arr;
console.log(id1, id2, id3);
//print: 1 2 3
객체 디스트럭처링
const user = { name: "Hong", passwd: "xyz", addr: "Seoul" };
function getUserValueExceptInitial(k) {
const { [k]: val } = user;
const [, ...result] = val;
return result.join(""); array로 만들어지기 때문에 join을 하여 구분자를 없애준다
}
console.log(getUserValueExceptInitial("name")); // 'ong'
// 아래와 같이 생각하는게 편할 듯
const key = "name";
const newObj = {
[key]: 'value'
};
'JavaScript' 카테고리의 다른 글
| [JS] 메모이제이션 (0) | 2025.04.09 |
|---|---|
| [JS] 스코프 실행컨텍스트 (0) | 2025.04.08 |
| [JS] Strict Mode (0) | 2025.04.08 |
| [JS] 호이스팅 (0) | 2025.04.07 |
| [JS] 데이터 타입 (1) | 2025.04.03 |