yuzunsang / JS-deep-dive-study

자바스크립트 딥 다이브 스터디✨
0 stars 3 forks source link

[CH35]스프레드 문법 #44

Open yuzunsang opened 2 months ago

yuzunsang commented 2 months ago

[퀴즈 예시] Q. 여기에 퀴즈 설명을 적으세요.

적을 코드가 있다면 밑에 적어주세요. (백틱 3개로 코드를 감싸면 코드 양식을 적을 수 있습니다.)

// 예시 코드
const arr = [1, 2, 3];
console.log("Hello");

아래 코드를 복붙해서 정답을 적어주세요.

<details>
    <summary>정답</summary>
    <div markdown="1">    
    정답 설명
    </div>
</details>
yuzunsang commented 2 months ago

예상 결과대로만 나오면 모두 정답입니다!!

Q1. 스프레드 문법을 이용해 addItem 함수를 완성하세요. [예상 결과] button 클릭 시 => items [1, 2, 3, 4, 5]

import { useState } from 'react';

function Item1() {
  const [items, setItems] = useState([1, 2, 3]);

  const addItems = () => {
    // ??
  }

  return (
    <div>
      <button onClick={() => addItems([4, 5])}>아이템 추가</button>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

Q2. 스프레드 문법을 이용해 insertItemAt 함수를 완성하세요. [예상 결과] button 클릭 시 => items [1, 99, 2, 3]

import { useState } from 'react';

function Item2() {
  const [items, setItems] = useState([1, 2, 3]);

  const insertItemAt = (index, newItem) => {
    // ??
  };

  return (
    <div>
      <button onClick={() => insertItemAt(1, 99)}>아이템을 중간에</button>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}
1번 정답
setItems((prevItems) => [...prevItems, ...newItems]);
2번 정답
setItems((prevItems) => {
const newItems = [...prevItems];
newItems.splice(index, 0, newItem);
return newItems;
});
bo-eun commented 2 months ago

Q. 스프레드 문법을 사용하여 기존 객체 person에 새로운 속성 age: 30을 추가한 새로운 객체를 만드세요.

const person = { name: 'Alice', city: 'Wonderland' };
정답
const newPerson = { ...person, age: 30 };