본문 바로가기
프로그래밍언어/JavaScript

[Javascript] 비 구조화 할당

by Yikanghee 2022. 4. 6.
  • 배열, 객체에서 원하는 값을 쏙쏙 빼오는 방법 비 구조화 할당
  • 배열의 비구조 할당
let arr = ["one", "two", "three"];

let one = arr[0];
let two = arr[1];
let three = arr[2];

console.log(one, two, three);

---------------------------------------

let arr = ["one", "two", "three"];

let [one, two, three] = arr;
console.log(one, two, three);
// 대괄호에 있는 내용을 할당 받아서 사용
// 이것을 비 구조화 할당이라고 함
// 배열의 기본구조 비 구조화 할당

---------------------------------------

let [one, two, three] = ["one", "two", "three"];

console.log(one, two, three);
// 배열의 선언분리 비 구조화 할당
// one two three

---------------------------------------

let [one, two, three, four] = ["one", "two", "three"];

console.log(one, two, three, four);
// 배열의 선언분리 비 구조화 할당
// one two three undefined

---------------------------------------

let [one, two, three, four = "four"] = ["one", "two", "three"];

console.log(one, two, three, four);
// 배열의 선언분리 비 구조화 할당
// one two three four
//기본값을 설정하여 undefined를 막을 수 있음
  • 스왑
let a = 10;

let b = 20;

let tmp = 0;

tmp = a;
a = b;
b = tmp;
console.log(a,b);
//20 10
//a, b 값이 스왑됐음

---------------------------------------

let a = 10;
let b = 20;

[a,b] = [b,a];
console.log(a,b);
//20 10
//a, b 값이 스왑됐음
  • 객체의 비구조 할당
let object = { one: "one", two: "two", three:"three"};

let one = object["one"];
let two = object.two;
let three = object.three;

console.log(one, two, three);
//one two three

---------------------------------------

let object = { one: "one", two: "two", three:"three"};

let {one, two, three } = object;
console.log(one, two, three);
//one two three

---------------------------------------

let object = { one: "one", two: "two", three:"three", name: "Tom"};

let {name, one, two, three } = object;
console.log(one, two, three, name);
//one two three Tom
//객체의 비구조 할당은 Key값으로 이루어짐
//그래서 순서와 상관없음

---------------------------------------

let object = { one: "one", two: "two", three:"three", name: "Tom"};

let {name : myName, one, two, three } = object;
console.log(one, two, three, myName);
//one two three Tom
//객체의 비구조 할당은 Key값으로 이루어짐
//그래서 value 값에 명칭을 지정해주어 가져올수있음

댓글