[VANILA JS NINJA] Vanila Javascript Project - DOM Array Methods (21/05/03)

NinjaJuunzzi·2021년 5월 2일
0

[VANILA JS NINJA]

목록 보기
1/9

DOM Array Methods

Array Methods를 테스트 해볼 수 있는 바닐라 자바스크립트 프로젝트를 만들어보자

1. createElement 복습

  • User.createNode()
  createNode = () => {
    const node = document.createElement("h3");
    const name = document.createElement("strong");
    const moneytag = document.createTextNode(this.money);
    name.innerText = this.name;
    node.appendChild(name);
    node.appendChild(moneytag);
    return node;
  };

📖 document

사용 의 createElement () 메소드는 지정된 이름의 요소 노드를 만들 수 있습니다.

🐌 느낀점

  • 요소 생성과 텍스트 값 넣기
<h1>text node value</h1>

  • 요소 생성과 아이디 값 넣기

2. appendChild 복습

  • User.createNode()
  createNode = () => {
    const node = document.createElement("h3");
    const name = document.createElement("strong");
    const moneytag = document.createTextNode(this.money);
    name.innerText = this.name;
    node.appendChild(name);
    node.appendChild(moneytag);
    return node;
  };

📖 document

Node.appendChild() 메소드는 한 노드를 특정 부모 노드의 자식 노드 리스트 중 마지막 자식으로 붙입니다. 만약 주어진 노드가 이미 문서에 존재하는 노드를 참조하고 있다면 appendChild() 메소드는 노드를 현재 위치에서 새로운 위치로 이동시킵니다. (문서에 존재하는 노드를 다른 곳으로 붙이기 전에 부모 노드로 부터 지워버릴 필요는 없습니다.)

🐌 느낀점

  • appendChild() 시 기존 노드에서 삭제 후 옮길 필요 없다
    알아서 이동함..........

3. 마지막 자식의 텍스트 값 바꾸기

  • double()
const double = () => {
    users.forEach((user) => {
      user.money = user.money * 2;
      user.node.lastChild.textContent = user.money;
    });
  };

🐌 느낀점
어떻게 해야할까 조금 고민했다.(...조금) 처음에는 자식을 없애고 새롭게 추가해줘야 하나? 아니면 자식을 덮어쓸까? 이렇게 생각했는데..
후자가 맞았다
textContent는 자식요소의 텍스트 값 속성이다. 이를 변경하면 자식요소 텍스트값 변경 가능!!

4. array.reduce

  • calculateWealth() only appendChild [bad]
const calculateWealth = () => {
    main.appendChild(
      document.createTextNode(
        users.reduce((accumulator, current) => accumulator + current.money, 0)
      )
    );
  };
  • calculateWealth() appendChild & removeChild [good]
 calculateWealth = () => {
    if (this.main.contains(this.entireWealth)) {
      this.main.removeChild(this.entireWealth);
      return;
    }
    this.entireWealth.innerText = this.users.reduce(
      (accumulator, current) => accumulator + current.money,
      0
    );
    this.main.appendChild(this.entireWealth);
  };

🐌 느낀점
처음 써보는 array 함수였다. reducer(in redux) 같기도 ?
자바스크립트 특성상 초기 값을 0으로 넣어주어야 정수계산이된다.
초기값을 0으로 넣지 않으면 문자열 계산이 되어서 숫자 문자열들이 쭉 이어짐. 체크요망
기존의 자식요소가 존재하면 다시 자식요소를 붙이지 않는다.
기존의 자식요소가 없으면 계산해서 다시 자식요소를 붙인다.

리듀서 함수는 네 개의 인자를 가집니다. 계산되는 값accumulator (acc)
현재 값 (cur)
현재 인덱스 (idx)
원본 배열 (src)

reduce 함수는 reducer와 initialValue를 인자로 갖는다.

5. array.sort

  • sort() - css order를 이용한 순서대로
 const sort = () => {
    main.style = "display:flex; flex-direction:column;";
    users = users.sort((a, b) => {
      if (a.money > b.money) {
        return -1;
      }
      if (a.money < b.money) {
        return 1;
      }
      return 0;
    });
    users.forEach((user, index) => (user.node.style.order = index));
  };

sort도 처음 써보는 함수... sort(compare) 이 때 compare() 입 맛에 맞게 수정가능!
배열을 우선 소트한 후 => 배열 순서대로 order값을 주어 순서대로 보이게하였다. => 하지만 나중에 요소를 추가하는 경우 이상한 곳에 들어감( 오더 값이 디포트라 다른 것보다 우선 순위 높게 책정됨)

  • sort() - 렌더링 된 자식요소를 전부 지우고 새로운 배열로 자식요소를 채운다.(replace)
sort = () => {
    this.users.forEach((user, index) => {
      this.main.removeChild(user.node);
    });
    this.users = this.users.sort((a, b) => {
      if (a.money > b.money) {
        return -1;
      }
      if (a.money < b.money) {
        return 1;
      }
      return 0;
    });
    this.users.forEach((user, index) => {
      this.main.appendChild(user.node);
    });
  };
this.users.forEach((user, index) => {
      this.main.removeChild(user.node);
});

기존 배열의 요소들을 main 요소에서 배제시킨다.

this.users.forEach((user, index) => {
      this.main.appendChild(user.node);
    });

소트된 배열의 요소들을 main 요소에 추가한다.

📖 document
도큐멘트에 나와있는 컴페어 예시임.

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

🐌 느낀점

  • replaceChild() 는 뭘까?
  • appendChild() 시 기존 노드 삭제할 필요없음
    sort = () => {
       this.users = this.users.sort((a, b) => {
         if (a.money > b.money) {
           return -1;
         }
         if (a.money < b.money) {
           return 1;
         }
         return 0;
       });
       this.users.forEach((user, index) => {
         this.main.appendChild(user.node);
       });
     };



## 6. await async 복습
- `init()` 
다음과 같이 하면 안된다. `init()`이 비동기 함수가 되어서 `await init()` 해주어야함.

```javascript 
const init = async () => {
  const user1 = await getUser();
  const user2 = await getUser();
  const user3 = await getUser();
  peoples.push(user1);
  peoples.push(user2);
  peoples.push(user3);
  console.log(peoples);//[user1,user2,user3]
};
init();
console.log(peoples); //[]

[baaaaad]

[gooooood]

비동기 함수를 사용하는 경우 호출하는 함수에서 async - await 붙여주자.

const fetcher = async () => {
  const {
    results: [user],
  } = await (await fetch("https://randomuser.me/api/")).json();
  return new User(user); 
};
  • 호출하는 함수에서 await fetcher 해주면 제대로 감.
  • 호출하는 함수에서 await 안해주면 프로미스옴 이 프로미스를 풀어야 User 객체 온다.

🐌 느낀점

  • 호출 하는 곳에서도 비동기 처리를 해주어야 프로미스가 아닌 결과물이 온다.!!!

완성 코드

깃허브 링크

프론티어 느낀점

  • res.json()은 두 번 못한다.
  • +data[1] => 문자열을 정수로

Reference

profile
Frontend Ninja

0개의 댓글