배열, 객체에서 원하는 값을 쉽고 빠르게 구할 수 있는 방법
let arr = ["one", "two", "three"];
let one = arr[0];
let two = arr[1];
let three = arr[2];
console.log(one, two, three);
let [one, two, three] = arr;
//대괄호를 이용해서 배열의 요소를 할당 받는 방법 => 비 구조화 할당
//배열은 인덱스를 통해 할당 받는다. 순서대로..?
console.log(one, two, three);
let [one, two, three] = ["one", "two", "three"];
//스왑 let a = 10; let b = 20; [a, b] = [b, a]; console.log(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);
let object = { one: "one", two: "two", three: "three", name: "nnnn" };
let { name, one, two, three } = object;
//객체의 비구조화 할당은 객체의 키값을 이용해 할당된다.
//즉 순서가 아니라 키값을 {}안에 넣어줘야만 프로퍼티 키가 가지고 있는 값을 할당 받을 수 있다.
console.log(one, two, three, name); //one two three nnnn
따라서 변수명이 키값으로 강제되는 경우가 있다.
let object = { one: "one", two: "two", three: "three", name: "nnnn" };
let { name: myName, one: ONE, two: TWo, three, abc = "four" } = object;
console.log(ONE, TWo, three, myName, abc); //one two three nnnn
즉 비구조화 할당할때 :
을 이용해 다른 변수명을 지정해 주면 된다.