본문 바로가기

JAVASCRIPT

구조분해할당-기초?예시

배열이나 객체의 속성을 해체하여 그 값을 개별 변수에 담을 수 있게하는 javaScript 표현식입니다.

 

 

let a, b, rest;
[a, b] = [10, 20];

console.log(a);
// Expected output: 10

console.log(b);
// Expected output: 20

[a, b, ...rest] = [10, 20, 30, 40, 50];

console.log(rest);
// Expected output: Array [30, 40, 50]

위의 코드를 말로 푼다면

[10,20]배열을 [a,b]에 하나씩 할당을 해주면서 a = 10, b= 20이 되게됩니다.

 

이제 객체를 분해해보겠습니다.

let demo = {c:123,d:"too"}
let {c,d} = demo;

console.log(c)
//output : 123

console.log(d)
//output : "too"

console.log(typeof c)
//output : "number"

console.log(typeof d)
//output: "string"

demo의 각자의 key로 해당하는 value를 할당 받게 되었습니다.

 

function f() {
  return [1, 2, 3];
}

var [a, , b] = f();
console.log(a); // 1
console.log(b); // 3

필요하지 않는 반환값을 무시 할수 있습니다.

 

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

'JAVASCRIPT' 카테고리의 다른 글

Bcrypt - 단방향 암호화  (0) 2023.03.29
Error : data must be a string or Buffer and hash must be string  (0) 2023.03.28
app.get VS router.get  (0) 2023.03.26
RegExp(정규표현식)  (0) 2023.03.25
비동기처리(callback, async/await)  (0) 2023.03.23