JavaScript 배열 구조 분해 시 기본값 설정
변수에 기본값을 지정할 수 있습니다. 이 경우, 변수에 배열 요소가 부족할 때 기본값이 사용됩니다. 다음 예제에서 변수 day의 기본값은
let arr = [2025, 12];
let [year, month, day = 1] = arr;
console.log(year); // 2025를 출력
console.log(month); // 12를 출력
console.log(day); // 1을 출력
반면에 변수 day에 배열에 값이 존재한다면, 기본값은 무시됩니다:
let arr = [2025, 12, 31];
let [year, month, day = 1] = arr;
console.log(year); // 2025를 출력
console.log(month); // 12를 출력
console.log(day); // 31을 출력
다음 코드에서는 배열의 일부가 해당 변수에 저장됩니다:
let arr = ['John', 'Smit', 'development', 'programmer'];
let name = arr[0];
let surname = arr[1];
let department = arr[2];
let position;
if (arr[3] !== undefined) {
position = arr[3];
} else {
position = 'trainee';
}
배운 이론에 따라 이 코드를 구조 분해를 사용하도록 변경하세요.