본문 바로가기
Front-End/javascript

[Javascript 기초] 전개 연산자

by 김기. 2023. 6. 3.

전개 연산자는 배열의 요소나 객체를 전개해주는 연산자입니다.

배열이나 객체를 복사하여 여러 개의 배열이나 객체를 병합할 수 있습니다.

// 구문
 myFunction(...iterableObj);

1. 배열에서의 전개 연산자

// 배열 복사
let colors = ["red", green, "blue"];
let colors2 = ["pink, ...arr"];
console.log(arr2); // ['pink', 'red', 'green', 'blue']

// 배열 병합
let hobby = ["game", "sports", "reading"];
let hobby2 = ["dance", "climbing", "skating"];
let newHobby = [...hobby, ...hobby2];
console.log(newHobby); // ['game', 'sports', 'reading', 'dance', 'climbing', 'skating']

 

2. 객체에서의 전개 연산자

let defaults = {
color: "black",
hobby: "nap",
address: "nowhere"
}

let customs = {
color: "red",
address: "seoul"
}

let newObj = {...default, ...customs}

console.log(newObj); // {color: 'red', hobby: 'nap', address: 'seoul'}

댓글