배열 디스트럭처링 Array Destructuring(ES6)

sangwoo noh·2021년 7월 2일
0

JavaScript

목록 보기
2/16
post-thumbnail

기본 사용법

const arr = [1, 2, 3];
const [one, two, three] = arr;
console.log(one, two, three); // 1 2 3

예시1

let x, y, z;
[x, y, z] = [1, 2, 3];
// 위의 구문과 같은 의미
let [x, y, z] = [1, 2, 3];

예시2

let x, y, z;
[x, y] = [1, 2];
console.log(x, y); // 1 2

[x, y] = [1];
console.log(x, y); // 1 undefined

[x, y] = [1, 2, 3];
console.log(x, y); // 1 2

[x, , z] = [1, 2, 3];
console.log(x, z); // 1 3

[x, y, z = 3] = [1, 2];
console.log(x, y, z); // 1 2 3

with Spread

[x, ...rest] = [1, 2, 3];
console.log(x, rest); 
// 1 [ 2, 3 ]

기본값 지정

//값이 없는 경우 y에 5를 할당하고 값이 존재하면 무시한다.

[x, y = 5, z = 3] = [1, 2];
console.log(x, y, z); // 1 2 3
(y값이 존재하니 할당안됨)
profile
하기로 했으면 하자

0개의 댓글