🤍 전 강의 25% 할인 중 🤍

2024년 상반기를 돌아보고 하반기에도 함께 성장해요!
인프런이 준비한 25% 할인 받으러 가기 >>

  • 카테고리

    질문 & 답변
  • 세부 분야

    프로그래밍 언어

  • 해결 여부

    미해결

참가 인원 재입력 과정 추가

21.12.10 16:39 작성 조회수 188

0

안녕하세요, 선생님.

 

제가 이번 끝말잇기 게임 만들기 강조를 마무리하면서 1) 게임 시작 시 입력받은 게임 참가 인원을 확인(confirm) 하고 2) 이용자가 '취소' 버튼 클릭 시, 3) 재입력 하도록(prompt) 코드를 만들어봤는데요.

이 때 먼저 const yesorno = confirm('입력하신 게 맞나요?') 선언하고, 

if (yesorno==true) ~ 를 이용했습니다. 그런데 실제 프로그램을 돌려보니 두번 확인하다가 멈췄는데요. 계속 취소를 누를 경우, 재입력 할 수 있는 prompt창이 계속 떠야한다고 생각하는데, 그렇지 않아 어디서 놓친 부분이 있는지 궁금합니다.

 

코드 >

      if (yesorno == true) {
            const onClickButton = () => {
                if (!word || word[word.length - 1] === newWord[0]) { //제시어가 비어있다
                    word = newWord;
                    $word.textContent = word;
                    // document.getElementById("word").innerText = word;
                    const order = Number($order.textContent);
                    if (order + 1 > number) {
                        $order.textContent = 1;
                    } else {
                        $order.textContent = order + 1;
                    }
                } else { //제시어가 있음
                    alert('올바르지 않은 단어입니다. 게임종료')
                    $order.textContent = 1;
                    $word.textContent = '';
                }

                $input.value = '';
                $input.focus();
            };
        } else {
            const number = parseInt(prompt("몇 명이 참가하나요?"), 10);
            const yesorno = confirm('입력하신 게 맞나요?');
        }

 

답변 1

답변을 작성해보세요.

0

왜 두 번 후에 멈추냐면 else 문 안에 있는 const yesorno는 아무데서도 쓰이지 않기 때문입니다.

코드는 위에서 아래로만 갑니다. 그래서 처음 if문으로 다시 돌아가지 않습니다.

다만 아래에서 위로 가는 경우가 하나 있죠. 바로 반복문입니다.

그래서 반복문(for, while)을 통해서 yesorno가 false인 경우 무한히 다시 재입력하게 하는 로직이 필요합니다.

왜 안되는지 이해 되어 while 문으로 바꿔 작성해보았습니다.

const number = parseInt(prompt("몇 명이 참가하나요?"), 10);
        const yesorno = confirm('입력하신 게 맞나요?');

        while (yesorno == false){
        const number = parseInt(prompt("몇 명이 참가하나요?"), 10);
        const yesorno = confirm('입력하신 게 맞나요?');
        };
    
            const onClickButton = () => {
                if (!word || word[word.length - 1] === newWord[0]) { //제시어가 비어있다
                    word = newWord;
                    $word.textContent = word;

(코드후략)

yesorno == false 인 경우 인원수와 그것을 확인하는 과정이 계속 반복되도록 아래와 같이 작성했는데 확인 과정에서 '확인(true)' 버튼을 눌러도 계속 인원수 입력과 확인 과정을 반복합니다.코드 흐름상 오류가 있는걸까요?

 

아니면 const number =parseInt(prompt('몇 명이 참가하나요?'), 10)과  const yesorno= confirm('입력하신 게 맞나요?');가 while문에 있는 것이 문제일까요?

두 번째 number와 yesorno 앞에 const를 떼세요. const를 붙이면 서로 다른 변수가 됩니다(const를 붙이면 새로 변수를 선언하는 것이고, const가 없으면 기존 변수의 값을 수정하는 겁니다)

둘 다 const를 뺄 경우, 두번째로 인원수를 새로 받고 난 후 아예 끝이 나고 html 화면 창이 나타납니다. 즉, 다시 인원수를 확인하는 과정이 실행되지 않습니다..!

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

<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 = parseInt(prompt("몇 명이 참가하나요?"), 10);
        // const yesorno = confirm('입력하신 게 맞나요?');

        const $button = document.querySelector('button');
        const $input = document.querySelector('input');
        const $order = document.querySelector('#order');
        const $word = document.querySelector('#word');

        let word; //제시어
        let newWord; //새로 입력한 단어

        const number = parseInt(prompt("몇 명이 참가하나요?"), 10);
        const yesorno = confirm('입력하신 게 맞나요?');

        while (yesorno == false){
        number = parseInt(prompt("몇 명이 참가하나요?"), 10);
        yesorno = confirm('입력하신 게 맞나요?');
        };
        
    
            const onClickButton = () => {
                if (!word || word[word.length - 1] === newWord[0]) { //제시어가 비어있다
                    word = newWord;
                    $word.textContent = word;
                    // document.getElementById("word").innerText = word;
                    const order = Number($order.textContent);
                    if (order + 1 > number) {
                        $order.textContent = 1;
                    } else {
                        $order.textContent = order + 1;
                    }
                } else { //제시어가 있음
                    alert('올바르지 않은 단어입니다. 게임종료')
                    $order.textContent = 1;
                    $word.textContent = '';
                }

                $input.value = '';
                $input.focus();
            }
        

        

        const onInput = (event) => {
            newWord = event.target.value;

        };

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


</body>

</html>
채널톡 아이콘