Javascript
구조 분해 할당 표현식
maybe.b50
2020. 2. 21. 18:09
구조 분해 할당 구문은 배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게 하는 표현식입니다.
- 구조 분해 할당 표현식
- spread 연산자
- rest 파라미터
비구조할당(구조분해 할당) 표현식
배열에서의 구조분해할당 표현식
1
2
3
4
5
6
|
// 기본 변수 할당
var foo = ['one', 'two', 'three'];
var [one, two, three] = foo;
console.log(one); // 'one'
console.log(two); // 'two'
console.log(three); // 'three'
|
선언에서 분리한 할당
1
2
3
4
5
|
var c, d;
[c, d] = [1, 2];
console.log(c); // 1
console.log(d); // 2
|
기본값 : 변수에 기본값을 할당하면 분해한 값이 undefiend일때 그 값을 대신 가져온다.
1
2
3
4
|
var e, f;
[e=1, f=2] = [30];
console.log(e); // 30
console.log(f); // 2
|
변수값 교환하기
1
2
3
4
5
|
var a = 1;
var b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1
|
함수가 반환한 배열 분석
1
2
3
4
5
6
7
8
9
|
function f() {
return [1, 2];
};
var a, b;
[a, b] = f();
console.log(a); // 1
console.log(b); // 2
|
Spread 연산자
배열을 분해
반응형