3.5 JavaScript 전개 연산자

지구·2023년 7월 18일
0

JavaScript

목록 보기
10/30

전개 연산자(Spread Operator)

const a = [1, 2, 3]

console.log(a) // [1, 2, 3]
console.log(1, 2, 3) // 1, 2, 3

// 전개 연산자
console.log(...a) // 1, 2, 3

대괄호 기호만 없어지고 안에 있는 내용 남겨 진다.

전개 연산자 활용 1 - 배열

const a = [1, 2, 3]
const b = [4, 5, 6]

const c = a.concat(b)
console.log(c) // [1, 2, 3, 4, 5, 6]

const d = [a, b]
console.log(d) // [[1, 2, 3], [4, 5, 6]]

const d = [...a, ...b]
console.log(d) // [1, 2, 3, 4, 5, 6]

전개 연산자 활용 2 - 객체

const a = { x: 1, y: 2 }
const b = { y: 3, z: 4 }

const c = Object.assign({}, a, b)
console.log(c) // {x: 1, y: 3, z: 4}

const d = {a, b)
console.log(d) // { a: { x: 1, y: 2 ), b: { y: 3, z: 4 } }

const d = {...a, ...b)
console.log(d) // { x: 1, y: 3, z: 4 }

전개 연산자 활용 3

function fn(x, y, z) {
	console.log(x, y, z)
}

fn(1, 2, 3) // 1, 2, 3

const a = [1, 2, 3]
fn(a[0], a[1], a[2]) // 1, 2, 3
fn(...a) // 1, 2, 3
profile
프론트엔트 개발자입니다 🧑‍💻

1개의 댓글

comment-user-thumbnail
2023년 7월 18일

아주 유용한 정보네요!

답글 달기