zenghyun
2022. 12. 29. 16:08
숫자를 반환하는 함수를 만들어보자
조건
1. 입력 값이 ''이거나 prompt에서 취소를 누르면 null 값 표시
2. 입력 값이 숫자가 아니면 다시 prompt 호출
<!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>Document</title>
</head>
<body>
<script>
function readNumber(){
let question;
do{
question = prompt('Enter a number please?', '0');
}
while(!isFinite(question));
if( question === null || question === '')
return null;
return +question;
};
alert(`Read : ${readNumber()}`);
</script>
</body>
</html>
후기
처음에는 do while을 사용할 생각을 못했다.
그래서 문자를 입력받으면 다시 호출해야 하는데 여기서 return readNumber();를 사용했다.
하지만, 함수 본인이 자신을 계속 호출하는 방법을 사용하고 싶지 않아서 고민하다 do while을 사용하니 해결이 됐다.