spread operator(펼침연산자), Array.from()

박민형·2022년 5월 26일
0
post-thumbnail

📌 spread operator

🔎 개념

👉 배열의 아이템을 펼친다고 생각하면 됩니다.
👉 아이템을 복사할 때 깊은 복사를 수행 하기 때문에 이전의 배열과 spread operaotr로 수행한 새로운 배열은 다름 => 같은 곳을 참조 하지 않음

  let pre = ["apple", "orange", "watermelon"]
  // pre의 item들을 가져오기(펼쳐기)
  let newData = [...pre]

  console.log(newData) // ["apple", "orange", "watermelon"]
  
  newData[0] = "banana";
  console.log(newData[0]); // banana
  console.log(pre[0]); // apple

🔎 객체를 복사 할때

👉 배열 안에 객체가 있는 경우 객체는 참조값이므로 얕은복사 수행

  arr1 = [{name: 'park', id: 1}];
  arr2 = [...arr1];

  arr2[0].name = "kim"

  console.log(arr1[0].name) // Kim
  console.log(arr2[0].name) // Kim

🔎 spread operaotr 함수에서 사용

  function sum(a, b, c) {return a+b+c;}

  let pre = [100, 200, 300]
  // 600
  console.log(sum(...pre)) 

📌 Array.from()

🔎 개념

👉 배열로 만드는 메소드

  function addMark() {
      // arguments를 가짜 배열에서 진짜 배열로 만든다.
      let newArray = Array.from(arguments);
      let newData = newArray.map(function(value) {
	      return value + "!";
      }
                                 
	 // ['1!', '2!', '3!', '4!', '5!', '6!', '7!']
     console.log(newData);
   }

   addMark(1, 2, 3, 4, 5, 6, 7);

0개의 댓글