자바스크립트 배열 CRUD  (map, filter, slice, concat, spread연산자)

 

 

스프레드(전개)연산 ...
추가하기 concat
삭제하기(걸러내기) filter 
잘라내기 slice
반복하기 map (배열 전체복사)
수정하기 ...연산 응용

 

 

 

 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
 <script>
  // concat, filter, map, slice, 스프레드(전개) 연산자
  
  console.log("1. =============== 스프레드 연산자");
  const a = [1,2,3];
  const b = [...a];
  b.push(4); // b의 데이터 변경
  console.log(`a의 값은 : ${a}`); // 1,2,3
  console.log(`b의 값은 : ${b}`); // 1,2,3,4

  console.log("2. =============== 추가하기");
  const a2 = [1,2,3];
  const b2 = a2.concat(4);
  console.log(`a2의 값은 : ${a2}`); // 1,2,3
  console.log(`b2의 값은 : ${b2}`); // 1,2,3,4
  const c2 = [0, ...a2, 4];
  console.log(`c2의 값은 : ${c2}`); // 0,1,2,3,4

  console.log("3. =============== 걸러내기"); // 삭제하기
  const a3 = [1,2,3];
  const b3 = a3.filter((n)=> { return n !=1}); // bool을 return 받는다. -> true만 걸러낸다.
  console.log(`b3의 값은 : ${b3}`); // 2,3

  console.log("4. =============== 잘라내기");
  const a4 = [1,2,3];
  const b4 = a4.slice(0,2);
  console.log(b4); // [1,2]
  const c4 = [...a4.slice(0,2), 4, ...a4.slice(2,3)];
  console.log(c4); // [1,2,4,3]

  console.log("5. =============== 반복하기");
  const a5 = [1,2,3];
  //for(let i=0; i<a5.length; i++){
  //  console.log(a5[i]);
  //}
  // a5.forEach((n) => {console.log(n);}); // 리턴 못함.
  const b5 = a5.map((n) => n+10);  // const b5 = [...a5];
  console.log(b5);

const data = {phone:"2222"};
  const a6 = { id:1, name:"홍길동", phone:"1111", age:17, gender:"남"};
  const b6 = { ...a6, ...data}; //기존 데이터에 덮어씌움
  console.log(b6);


  const users = [
    {id:1, name:"구태모", phone:"2222"},
    {id:2, name:"이대엽", phone:"3333"},
    {id:3, name:"오승훈", phone:"4444"}
  ];

  const updateUserDto = {
    id:2, name:"홍길동"
  };

  const newUsers = users.
    map(user => user.id === updateUserDto.id ? {...user, ...updateUserDto} :user); // const newUser = {...users};
  
  console.log("newUsers", newUsers);
 </script>
</body>
</html>

결과 ( 깊은복사 )

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

 

import { useState } from 'react';
import './App.css';

function App() {
  // 다운로드 받음
  const [users, setUsers] = useState([
    { id: 1, name: '홍길동' },
    { id: 2, name: '임꺽정' },
    { id: 3, name: '장보고' },
    { id: 4, name: '코스' },
  ]);

  const download = () => {
    let sample = [
      { id: 1, name: '홍길동' },
      { id: 2, name: '임꺽정' },
      { id: 3, name: '장보고' },
      { id: 4, name: '코스' },
    ];

    setUsers([...sample]);
  };

  // 랜더링 시점 = 상태값 변경
  return (
    <div>
      <button onClick={download}>다운로드</button>
      {users.map((u) => (
        <h1>
          {u.id}, {u.name}
        </h1>
      ))}
    </div>
  );
}

export default App;

 

 

리엑트의 렌더링 시점 = 상태값 변경시점.
일반 변수를 상태 변수로 바꾸는법

React의 hooks 라이브러리를 사용함.
const [요소, set요소] = useState( );

ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡ

상태변수 이기때문에 원래있던 값에 변경된 값을 덮어씌우는 형식이다.

조금 더 다듬어서 저장하겠습니다.

+ Recent posts