[JS] 알고리즘 - 끝말잇기

chaeny·2020년 10월 15일

algorithm

목록 보기
6/6

알고리즘

let first = "첫글자";
let input = prompt("단어를 입력해주세요");

if (first[first.length-1] === input[0]) {
    first = input;
    input = prompt("단어를 입력해주세요");

    if (first[first.length-1] === input[0]) {
        first = input;
        input = prompt("단어를 입력해주세요");
    } else {
        console.log("틀렸습니다");
    }
} else {
    console.log("틀렸습니다");
}


반복문을 사용하면 될 것같다.
while문을 사용해 보자

let word = "첫글자";

while(true) {
    let input = prompt(word);

    if (word[word.length - 1] === input[0]) {
        word = input;
    } else {
        alert("틀렸어요");
    }
}


틀리면 게임종료를 시켜보자.

let word = "첫글자";
let isPlay = true;

while(isPlay) {
    let input = prompt(word);

    if (word[word.length - 1] === input[0]) {
        word = input;
    } else {
        alert("Game Over");
        isPlay = false;
    }
}


while문 보다 for문이 많이쓰인다
for문으로 만들어보자.


for (let word = "첫글자"; true;) {
    let input = prompt(word);

    if (word[word.length - 1] === input[0]) {
        word = input;
    } else {
        alert("틀렸어요");
    }
}


반복문의 기초적인 틀에 사로잡히지 말자. ⭐



웹사이트 구현

const body = document.querySelector("body");
const div = document.createElement("div");
const input = document.createElement("input");
const button = document.createElement("button");
const value = document.createElement("div");
div.textContent = "첫글자";
button.textContent = "입력";
body.append(div, input, button, value);

function handleClickbutton() {
    const word = div.textContent;
    const inputWord = input.value;
    input.value = "";
  
    if (word[word.length - 1] === inputWord[0]) {
        value.textContent = "맞았습니다.";
        div.textContent = inputWord;
    } else {
        value.textContent = "틀렸습니다.";
    }
}

button.addEventListener("click", handleClickbutton);

appendChild 보다 append가 코드 최적화에 유리하지 않을까?

0개의 댓글