티스토리 뷰
객체나 배열을 풀어 쓸 수 있다.
배열
const arr = ["a", "b", "c", "d"];
위 배열을 각각의 변수에 담아야 한다고 치자.
원래의 방법이라면
const arr = ["a", "b", "c", "d"];
const first = arr[0];
const second = arr[1];
const third = arr[2];
const fourth = arr[3];
console.log(first, second, third, fourth)
이렇게 써야 하지만
구조분해할당을 쓰게되면
const arr = ["a", "b", "c", "d"];
const [first, second, third, fourth] = arr
console.log(first, second, third, fourth)
이런 방법으로 써줄 수 있다.
왼쪽부터 차례대로 배열의 순서대로 할당된다.
let a, b, c
[a, b, c] = ["a", "b", "c"];
console.log(a, b, c)
이런식의 할당도 가능하다.
객체
const OBJ = {name:"kim", age:23}
const name = OBJ.name
const age = OBJ.age
console.log(name, age)
기존의 객체에서 값을 빼와서 변수에 담으려면
이렇게 했지만
구조분해 할당을 이용하면
const OBJ = {name:"kim", age:23}
const {name, age} = OBJ
console.log(name, age)
이런식으로 쓸 수 있다.
배열과 다른점은
변수로 지정한 2번째 열에서 객체의 순서대로 변수에 담는것이아닌,
객체의 프로퍼티를 빼는 것이다.
그렇기때문에
const OBJ = {name:"kim", age:23}
const {a, b} = OBJ
console.log(a, b)
이런식으로 쓰면 undefined 를 출력하는것을 볼 수 있다.
중첩된 객체의 경우에는
const event = {
target:{
name:"kim",
age:23
}
}
const {target : {name}} = event
console.log(name)
이런식으로 꺼내 줄 수 있다.(필요한 부분만 꺼내는것도 가능하기에 위에서 name만 꺼냈다.)
만약 중첩이 여러개 겹친다면
const event = {
target:{
name:"kim",
age:23,
another:{
help:{
memo:{
listOne:"힘들다"
}
}
}
}
}
const {target : {another:{help:{memo:{listOne}}}}} = event
console.log(listOne)
이런 경악스러운 모습이 되지만 아무튼 이렇게도 쓸 수 있다.
'Study > script.js' 카테고리의 다른 글
[배열, react state]배열안에 객체 중복 파악하기 (0) | 2020.01.29 |
---|---|
[warning]Nested block is redundant no-lone-blocks (0) | 2020.01.27 |
[자바스크립트 배열]findIndex & reduce (0) | 2019.12.26 |
[자바스크립트 배열]filter() (0) | 2019.12.26 |
[자바스크립트 기초]반복문에서의 continue와 break (0) | 2019.12.20 |
댓글