JS 전개 연산자

  • 전개 연산자 (spreadOperator) : 나열형 자료(배열(Array)과 객체(Object))를 추출(왼)하거나 연결(오른)시 사용
  • 사용방법 : 변수명 앞에 마침표 세개를 연속적으로 작성한다. (…변수명)
  • 구분자에 대한 제한 : 배열 = [] / 객체 - {} / 함수 - ()

자바스크립트 (ES5 이하) <배열>에서 전개 연산자처럼 사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var array1 = ["one", "two"];
var array2 = ["three", "four"];

// 두개의 배열 합치기 - 1
var combine1 = [array1[0], array1[1], array2[0], array2[1]];
console.log(combine1); // ['one', 'two', 'three', 'four']

// 두개의 배열 합치기 - 2
var combine2 = array1.concat(array2);
console.log(combine2); // ['one', 'two', 'three', 'four']

// 두개의 배열 합치기 - 3
var combine3 = [].concat(array1, array2);
console.log(combine3); // ['one', 'two', 'three', 'four']
1
2
3
4
5
6
7
8
9
10
11
12
// [["one", "two"], ["three", "four"]];
var combine3_1 = [[], []]; // [0번 인덱스, 1번 인덱스]
// 실습 : push 메서드를 활용하여 위의 예시와 같은 형태를 구성하시오
var array1 = ["one", "two"];
var array2 = ["three", "four"];

combine3_1[0].push(array1[0]);
combine3_1[0].push(array1[1]);
combine3_1[1].push(array2[0]);
combine3_1[1].push(array2[1]);

console.log(combine3_1); // [["one", "two"], ["three", "four"]]
  • “||” (or 연산자)를 조합하면 배열의 요소가 존재하지 않을 때 기본값으로 “empty”라는 특정 지정값으로 적용 가능하다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var array1 = ["one", "two"];
var array2 = ["three", "four"];

var first = array1[0];
console.log(first); // one

var second = array1[1];
console.log(second); // two

var third = array1[2];
console.log(third); // undefined

var third = array1[2] || "empty";
console.log(third); // empty (string)

자바스크립트(ES6 이후) <배열>에서 전개연산자 사용

1
2
3
4
5
const array3 = ["one", "two"];
const array4 = ["three", "four"];

const combine4 = [...array3, ...array4];
console.log(combine4); // ['one', 'two', 'three', 'four']
1
2
3
const array3 = ["one", "two"];
const array4 = ["three", "four"];
const combine5 = [[...array3], []...array4]]; // [["one", "two"], ["three", "four"]]
1
2
3
4
5
const [first_arr, second_arr, third_arr, fourth_arr] = array3; // ["one", "two"]
console.log(first_arr); // one
console.log(second_arr); // two
console.log(third_arr); // undefined
console.log(fourth_arr); // undefined
  • 데이터의 값이 존재하지 않을 경우, 기본값으로 설정한 “empty”가 도출된다.
1
2
3
4
5
const [first_arr, second_arr = "empty", third_arr = "empty", fourth_arr] = array3; // ["one", "two"]
console.log(first_arr); // one
console.log(second_arr); // two
console.log(third_arr); // empty
console.log(fourth_arr); // undefined

REFERENCE
뷰(Vue.js) 프로그래밍 과정 _ 하이미디어 아카데미

  • © 2020-2025 404 Not Found
  • Powered by Hexo Theme Ayer