[JS] 배열합치기(concat, 전개연산자, push)

JH Cho·2022년 9월 3일
0

concat()

concat() mdn 바로가기

concat() 메서드는 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환합니다.(스트링도)

원본은 변하지 않음.
-----------------------
const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];

num1.concat(num2, num3);
----------------
const alpha = ['a', 'b', 'c'];

console.log(alpha.concat(1, [2, 3],[[4,5]], {name:'name', id:'id'}));
/*
["a", "b", "c", 1, 2, 3, [4, 5], [object Object] {
  id: "id",
  name: "name"
}]*/

배열의 경우 한번만 펼침. 중첩 배열은 그대로 들어감.
객체의 경우 펼쳐지지 않고 객체가 그대로 들어감.

... spread operator(전개연산자)

ES6에서 제공! MDN링크

let arr = [1, 2, 3];

console.log(...arr)
// 1 2 3 차례대로 출력.

---------------------
let arr = [1, 2, 3];
copy = [...arr]
// 요소들을 풀었다가 배열로 다시 감싼 독립 복사본
console.log(copy)
// [1, 2, 3] 똑같이 생긴 배열이지만 참조는 다름.
---------------------
let arr = [1, 2, 3];
function sum(x, y, z){
  return x+y+z;
}

console.log(sum(...arr)) // 6 
전개연산자 말고 그냥 arr 넣으면 인자가 하나만 들어가는 것이라 undefined

--------------------
let arr = [1, 2, 3];
let newArr = [...arr, 4, 5]

console.log(newArr)
--------------------
let arr = {name: 'Cho'}

let newArr = {...arr, name:'Park'}
console.log(arr)
console.log(newArr)
/*
[object Object] {
  name: "Cho"
}
[object Object] {
  name: "Park"
}
*/
--------------------

push()

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

arr1.push(arr2) //[1, 2, 3, [4, 5, 6]]
arr1.push(...arr2)//[1, 2, 3, 4, 5, 6]
profile
주먹구구식은 버리고 Why & How를 고민하며 프로그래밍 하는 개발자가 되자!

0개의 댓글