개발일기

자바스크립트 구조분해할당 본문

Javascript

자바스크립트 구조분해할당

황대성 2024. 3. 31. 01:55

1. 배열 구조분해할당

 

1-1 배열 요소에 접근하는 방법

const array = ["사과","바나나",'오렌지']

const apple = array[0]
const banana = array[1]
const orange = array[2]

console.log(apple,banana,orange)
// Expected output: 사과 바나나 오렌지

 

1-2 배열 요소에 구조분해할당으로 접근하는 방법

const array = ["사과","바나나",'오렌지']

const [apple,banana,orange] = array ;

console.log(apple,banana,orange)
// Expected output: 사과 바나나 오렌지

 

※ 주의할 점

배열은 요소의 인덱스값에 따라(?) 구조분해할당을 한다.

만약 사과와 오렌지의 값을 사용하고 싶다면 바나나 자리에 공백을 유지한다.

 

const array = ["사과","바나나",'오렌지']

const [apple,,orange] = array ;

console.log(apple,orange)
// Expected output: 사과 오렌지

 

 

2. 객체의 구조분해할당

 

2-1 객체 요소에 접근하는 방법

const object = {
    name : 'Jhon',
    age : 19,
    city : 'busan'
}

const name = object.name;
const age = object.age;
const city = object.city;

console.log(name,age,city)
// Expected output: Jhon 19 busan

 

2-2 객체 요소에 구조분해할당으로 접근하는 방법

const object = {
    name : 'Jhon',
    age : 19,
    city : 'busan'
}

const {name,age,city} = object

console.log(name,age,city)
// Expected output: Jhon 19 busan

 

※ 주의할 점

객체는 키값에 따라(?) 구조분해할당을 한다.

따라서 배열과 달리 순서와 상관없이 사용할 수 있다.

const object = {
    name : 'Jhon',
    age : 19,
    city : 'busan'
}

const {name,city} = object

console.log(name,city)
// Expected output: Jhon busan

 

3. 함수의 매개변수로 전달된 객체를 구조분해할당하기

const object = {
    name : 'Jhon',
    age : 19,
    city : 'busan'
}

const printUser = ({name,age,city}) => {
    console.log(name,age,city)
}

printUser(object)
// Expected output: Jhon 19 busan

 

'Javascript' 카테고리의 다른 글

함수 호이스팅  (0) 2024.07.18
메서드 기록해두기(split, slice, splice)  (0) 2024.06.10
객체 타입의 얕은 복사와 깊은 복사  (0) 2024.03.07
원시타입과 객체타입  (0) 2024.03.06
var와 let 그리고 호이스팅  (1) 2024.03.01