인프런 커뮤니티 질문&답변
4강 if문 중첩 줄이기 질문입니다
작성
·
843
0
응용으로 쿵쿵따의 중첩 if문을 줄여봤는데 else가 없는데도 중첩 if문인 경우는 어떻게 해야 하나요?
일단 이해한대로 줄여보긴 했는데 잘못된 방법으로 줄인 건지, 정석으로 줄인 건지 궁금합니다!
쿵쿵따 셀프체크랑은 좀 다른 코드입니다!
const number = parseInt(prompt('몇 명이 참가하나요?'), 10);
if (!number) {
alert('몇 명이 참가하는지 입력해주세요!');
}
if (number) {
const $input = document.querySelector('input');
const $button = document.querySelector('button');
const $word = document.querySelector('#word');
const $order = document.querySelector('#order');
let word;
let newWord;
const onClickButton = () => {
if (!word) {
word = newWord;
const order = parseInt($order.textContent);
if (!(2 === word.length || 3 === word.length)) {
alert('두 글자, 세 글자로 이루어진 단어로만 입력해주세요!');
word = null;
$input.value = '';
$input.focus();
return;
}
if (2 === word.length || 3 === word.length) {
$word.textContent = word;
if (!(order === number)) {
$order.textContent = order + 1;
$input.value = '';
$input.focus();
return;
}
if (order === number) {
$order.textContent = 1;
$input.value = '';
$input.focus();
}
}
return;
}
if (!(word[word.length - 1] === newWord[0] && word.length === newWord.length)) {
alert('틀렸습니다!');
$input.value = '';
$input.focus();
return;
}
if (word[word.length - 1] === newWord[0] && word.length === newWord.length) {
word = newWord;
$word.textContent = word;
const order = parseInt($order.textContent);
if (!(order === number)) {
$order.textContent = order + 1;
$input.value = '';
$input.focus();
return;
}
if (order === number) {
$order.textContent = 1;
$input.value = '';
$input.focus();
}
}
}
아래는 원본 코드입니다!
const number = parseInt(prompt('몇 명이 참가하나요?'), 10);
if (number) {
const $input = document.querySelector('input');
const $button = document.querySelector('button');
const $word = document.querySelector('#word');
const $order = document.querySelector('#order');
let word;
let newWord;
const onClickButton = () => {
if (!word) {
word = newWord;
const order = parseInt($order.textContent);
if (2 === word.length || 3 === word.length) {
$word.textContent = word;
if (order === number) {
$order.textContent = 1;
} else {
$order.textContent = order + 1;
}
} else {
alert('두 글자, 세 글자로 이루어진 단어로만 입력해주세요!');
word = null;
}
} else if (word[word.length - 1] === newWord[0] && word.length === newWord.length) {
word = newWord;
$word.textContent = word;
const order = parseInt($order.textContent);
if (order === 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);
} else {
alert('몇 명이 참가하는지 입력해주세요!');
}
답변 1
1






어떤 식으로 제거해야 하는게 맞을까요?? if문을 감싸고 있는 조건문에 제거해야 하는 if문 조건식이랑 동작문을 넣어준 후 제거해줘야 하나요?