Array Methods를 테스트 해볼 수 있는 바닐라 자바스크립트 프로젝트를 만들어보자
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>
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()
메소드는 노드를 현재 위치에서 새로운 위치로 이동시킵니다. (문서에 존재하는 노드를 다른 곳으로 붙이기 전에 부모 노드로 부터 지워버릴 필요는 없습니다.)
🐌 느낀점
double()
const double = () => {
users.forEach((user) => {
user.money = user.money * 2;
user.node.lastChild.textContent = user.money;
});
};
🐌 느낀점
어떻게 해야할까 조금 고민했다.(...조금) 처음에는 자식을 없애고 새롭게 추가해줘야 하나? 아니면 자식을 덮어쓸까? 이렇게 생각했는데..
후자가 맞았다
textContent는 자식요소의 텍스트 값 속성이다. 이를 변경하면 자식요소 텍스트값 변경 가능!!
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를 인자로 갖는다.
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()
는 뭘까?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);
};
User
객체 온다.🐌 느낀점