1010 TIL (1)

기멜·2021년 10월 10일
0

자바스크립트 독학

목록 보기
26/44

오늘도 화이팅!!
참조: 제로초 ES2021 자바스크립트 유튜브

첫 번째 사람인지 확인하기

끝말잇기

순서도를 그려서 전체적인 코드의 실행순서를 알아봅니다.

순서도를 잘게잘게 쪼개는 방법을 연습을 많이 해야한다. 절차적으로 생각해야한다. 연습을 많이 많이 하고 스스로 생각을 많이 해봐야한다. 순서도 그리는걸 부끄럽게 생각하지 말자. 주눅들지 말자.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>끝말잇기</title>
</head>
<body>
    <div><span id="order">1</span>번째 참가자</div>
    <div>제시어: <span id="word"></span></div>
    <input type="text">
    <button>입력</button>
<script>
    const number = Number(prompt('몇 명이 참가하나요?'));
    const $button = document.querySelector('button');
    const $input = document.querySelector('input');

    const onClickButton = () => {
    };
    const onInput = (event) => {
    };

    $button.addEventListener('click', onClickButton);
    $input.addEventListener('input', onInput);
</script>
</body>
</html>

첫번째 참가자는 제시어가 없다. 두번째 참가자부터 제시어가 생김. 그러므로 제시어가 없으면 첫번째 참가자겠구나 라고 생각해야한다.

코딩을 바꿔봅시다.

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>끝말잇기</title>
</head>

<body>
  <div><span id="order">1</span>번째 참가자</div>
  <div>제시어: <span id="word"></span></div>
  <input type="text">
  <button>입력</button>
  <script>
    const number = Number(prompt('몇 명이 참가하나요?'));
    const $button = document.querySelector('button');
    const $input = document.querySelector('input');
    const $word = document.querySelector('#word');
    const $order = document.querySelector('#order');

    let word; // 제시어
    let newWord; // 새로 입력한 단어
    const onClickButton = () => {
      if (!word) { // 제시어가 비어 있는가?
        // 비어있다.
        word = newWord; // 입력한 단어가 제시어가 된다.
        $word.textContent = word; // 입력한 단어가 제시어 옆에 표시된다.
        $input.value = ''; // 제시어를 입력하자마자 입력창이 빈다.
        const order = Number($order.textContent) // 문자열을 숫자열로 돌리기, 현재 순서
        if (order + 1 > number) {
          $order.textContent = 1; // textContent가 들어가면 자동으로 문자열로 반환함
    	  input.focus();
        } else {
          $order.textContent = order + 1;
        }
      } else {
        // 비어 있지 않다.
        if (word[word.length - 1] === newWord[0]) { // 올바른가 word의 마지막자리와 newWord의 첫번째 자리가 일치하냐
          word = newWord; // 현재 단어를 제시어에 저장한다.
          $word.textContent = word; //화면에 제시어 표시
          $input.value = ''; // 제시어를 입력하자마자 입력창이 빈다.
    	  input.focus();
          const order = Number($order.textContent) // 문자열을 숫자열로 돌리기, 현재 순서
          if (order + 1 > number) {
            $order.textContent = 1; // textContent가 들어가면 자동으로 문자열로 반환함
          } else {
            $order.textContent = order + 1;
          }
        } else { // 올바르지 않은가
          alert('올바르지 않은 단어입니다!');
          $input.value = ''; // 제시어를 입력하자마자 입력창이 빈다.
    	  input.focus();
        }
      }
    };
    const onInput = (event) => {
      newWord = event.target.value; // 글자를 입력할 때 새로운 단어에, 그 글자가 저장된다.
    };

    $button.addEventListener('click', onClickButton);
    $input.addEventListener('input', onInput);
  </script>
</body>

</html>

이렇게 하면 끝말잇기가 됩니다.
머릿속에 생각만 하지말고 직접 해보는게 중요합니다.

코드 사용법

입력태그.value // 입력창의 값을 가져옴
입력태그.value =// 입력창에 값을 넣음

또한 입력 태그를 선택하게 하려면 focus 라는 메서드를 사용합니다. focus 는 입력 태그 내부에 커서가 위치하게 해서 다음 사용자가 입력하기 편하게 도와줍니다.

코드 사용법

입력태그.focus() // 입력창을 하이라이트

내부 값을 가져오는 코드

입력태그.value // 입력창의 값을 가져옴
입력태그.value =// 입력창에 값을 넣음
태그.textContent // 태그 내부의 문자를 가져옴
태그.textContent =// 태그 내부의 문자를 해당 값으로 설정 

순서도 최적화하기

코드의 중복이 되는 부분이 많습니다. 이 부분을 정리해보도록 하겠습니다.

<body>
  <div><span id="order">1</span>번째 참가자</div>
  <div>제시어: <span id="word"></span></div>
  <input type="text">
  <button>입력</button>
  <script>
    const number = Number(prompt('몇 명이 참가하나요?'));
    const $button = document.querySelector('button');
    const $input = document.querySelector('input');
    const $word = document.querySelector('#word');
    const $order = document.querySelector('#order');

    let word; // 제시어
    let newWord; // 새로 입력한 단어
    const onClickButton = () => {
      if (!word || word[word.length - 1] === newWord[0]) { // 제시어가 비어 있는가? / 비어있다.
        word = newWord; // 입력한 단어가 제시어가 된다.
        $word.textContent = word;
        const order = Number($order.textContent); // 현재 순서
        if (order + 1 > number) {
          $order.textContent = 1;
        } else {
          $order.textContent = order + 1;
        }
      } else { // 올바르지 않은가
        alert('올바르지 않은 단어입니다!');
      }
      $input.value = ''; // 입력창을 빈 칸으로 만들어준다.
      $input.focus(); // 빈칸에 포커스 하이라이트를 해주는 메서드
    };
    const onInput = (event) => {
      newWord = event.target.value; // 글자를 입력할 때 새로운 단어에, 그 글자가 저장된다.
    };

    $button.addEventListener('click', onClickButton);
    $input.addEventListener('input', onInput);
  </script>
</body>

코드해석: 일단 let word (제시어) 랑 let newWord (새로 입력한 단어) 변수를 만들어 준다. 그 다음 onClickButton 이름을 가진 function을 만들고 if문을 만들어서 !word(true)을 부정 또는 word[word.length - 1] === newWord[0] 이라는 코드를 쓴다. 이렇게 되면 word 에word.length - 1 은 단어의 word단어의 마지막 글자랑 newWord[0]의 첫번째 글자가 같으면 true 라는 게 되어서 맞으면 실행이 된다. word = newWord로 해주면 입력한 단어가 제시어가 된다.
newWord가 word로 되고, $word.textContent = word; 는 $word.textContent로 글자만을 가져옵니다. 그래서 제시어: 옆에 적은 글자가 나타나게됩니다. 그리고 const order = Number($order.textContent); 로 $order 인 1을 가져오게 됩니다. order는 1이 되는 셈이죠. 그런데 if문에서 order + 1 이 number보다 커야한다고 했습니다. number는 몇 명이 참가할 겁니까를 나타낸 숫자니까 설정해준 숫자만큼인데. 2명 일 때도3명 일 때도 4명 일 때도 order는 1이기 때문에 1+1 해봤자 2이기 때문에 order + 1 이 더 크다라는 코드는 성립되지 않습니다. 그래서 false인 else코드가 실행되어서 2번째, 3번째 ~ 등등 나타낼 수 있는 것입니다. order의 숫자가 늘어나고 만약에 정원이 4명이라면 order의 숫자가 5가 되는 순간 if문이 성립되어 다시 숫자가 1로 바뀝니다. 그리고 밖에 if의 [word.length - 1] === newWord[0] 가 성립이 안되는 예를들어 '자바스크립트' -> '나비' 이렇게 적었다면 true가 되지않고 false가 되어서 둘 다 false가 되어 else문이 실행이 됩니다. 그리고 if문 밖에 적어준 $input.value = ''; 는 입력창을 빈 칸으로 만들어주고, $input.focus();는 빈칸에 포커스 하이라이트를 주는 메서드 를 적어줍니다. 그리고 const onInput = (event) => { newWord = event.target.value }; 라는 식을 만들어 글자를 입력할 때 새로운 단어에, 그 글자가 저장되게 합니다. $button.addEventListener('click', onClickButton); $input.addEventListener('input', onInput); 이 마지막 두 문장은 이벤트를 실행하라는 메서드입니다.

**논리 연산 구분
AND ( && ) 는 둘 다 true 여야합니다.
OR ( || ) 은 둘 다 false 여야하는데, 하나만 true가 있어도 true 입니다.

profile
프론트엔드 개발자를 꿈꾸는 도화지 위를 달리는 여자

0개의 댓글