Javascript

[JavaScript] 비구조화 할당

고줭 2022. 4. 5. 10:49
let arr = ["one", "two", "three"];

console.log(arr[0]);	// one
console.log(arr[1]);	// two
console.log(arr[2]);	// three
let [하나, 둘, 셋] = ["one", "two", "three"];

console.log(하나);    // one
console.log(둘);		// two
console.log(셋);		// three

일반적으로 배열의 값에 접근하려면 인덱스를 사용합니다. 자바스크립트의 비구조화 할당으로 인덱스없이 값에 접근할 수 있습니다.

 

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

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

객체의 경우도 가능하지만 four같이 처음 객체의 없는 것을 할당하는 경우 undefined가 나오기 때문에 초기값을 세팅할 수 있음