리액트

리액트 입문, concat, filter, map, slice, 스프레드

나는시화 2023. 11. 20. 11:44
<!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); // 데이터 변경
    console.log(`a의 값은 : ${a}`) // 1 2 3  
    console.log(`b의 값은 : ${b}`) // 1 2 3 4
    // 깊은 복사 : 값만 복사
    const c = [1, 2, 3];
    const d = c;
    c.push(4);
    console.log(`c의 값은 : ${c}`) // 1 2 3 4
    console.log(`d의 값은 : ${d}`) // 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

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

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

    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) }); // 리턴 void
    const b5 = a5.map((n) => n); // const b5 = [...a5]; 와 같음
    console.log(b5); // 1 2 3

  </script>
</body>

</html>