7) DOM

ppparkta·2022년 11월 14일
1

웹개발

목록 보기
8/26

이번주는 [레츠겟잇 자바스크립트 프로그래밍] 책 한단원 분량을 매일 학습한 뒤 다음날 해당 내용을 실습하기로 계획했다. 어제 3단원(dom객체 다루기)파트를 읽었기 때문에 오늘은 3단원 복습과 4단원 분량을 학습을 한다.

오늘 학습한 내용

  • 바닐라js 쿵쿵따 게임 제작
  • 바닐라js 4장 내용 정리
    • 고차함수

DOM 객체 다루기 실습

어제 읽었던 dom객체 다루기 파트의 self check과제를 끝냈다. 책을 안보고 스스로 복습해서 코드가 책에 비해 많이 더럽게 느껴진다. 다른 점도 많았다.

책에서는 order 변수를 함수 내부에 const로 선언해서 사용했는데, 나는 let으로 빼줬다.

<h1>쿵쿵따 게임</h1>
<div>
    <span id="human"></span>
    <span id="order"></span>
    <p>
        <span>제시어: </span><span id="word"></span>
    </p>
    <input id="word-input" type="text">
    <button id="btn">입력</button>
</div>
const $word=document.querySelector("#word");
const $wordInput=document.querySelector("#word-input");
const $btn=document.querySelector("#btn");
const $human=document.querySelector("#human");
const $order=document.querySelector("#order");
const number=prompt("인원을 입력해주세요.");
let word;
let newWord;
let order=1;

if(number){
    $human.textContent=`현재 인원은 ${number}명입니다.`;
}
if(!word){
    $order.textContent=`${order}번 차례입니다.`;
}
const onInput=(event)=>{
    newWord=event.target.value;
}
const onClickBtn=(event)=>{
    if(!word&&newWord.length===3){
        word=newWord;
        $word.textContent=word;
        $wordInput.value="";
    }
    else if(!word&&newWord.length!==3){
        alert("세글자 단어를 입력해주세요");
        $wordInput.value="";
    }
    else{
        if(word[word.length-1]===newWord[0]&&newWord.length===3){
            word=newWord;
            $word.textContent=word;
            $wordInput.value="";
            if(order+1>number)
            {
                order=1;
                $order.textContent=`${order}번 차례입니다.`;
            }
            else{
                order+=1;
                $order.textContent=`${order}번 차례입니다.`;
            }
        }
        else{
            alert("틀렸습니다. 다시 입력해주세요.");
            $wordInput.value="";
        }
    }
}
$wordInput.addEventListener("input",onInput);
$btn.addEventListener("click",onClickBtn);

자바스크립트 책이나 강의를 보면서 느끼는건데 많은 사람들이 변수보단 const사용을 더 좋아하는 것 같다. 볼륨이 커지다보면 변수를 하나하나 관리하기 어렵기 때문이라고 생각한다.


고차함수

func와 같이 함수 안에서 함수를 반환하는 함수를 고차함수라고 한다.

const func = (msg) =>{
	return () => {
    	console.log(msg);
    };
};

함수 본문에서 반환되는 값이 있으면 {return을 생략할 수 있다. 위와 아래의 함수는 같은 기능을 한다.

const func = (msg) => () => {
	console.log(msg);
};

실습으로 만들 계산기 앱에는 굳이 고차함수를 사용할 필요가 없지만, 대부분 다 비슷한테 특정 부분만 다른 함수는 많이 나오기 때문에 알아두면 좋다.

profile
겉촉속촉

0개의 댓글