1. 랜덤으로 숫자 가져오는 함수
function random() {
return Math.floor(Math.random() * 10)
}
Math.random()은 Math 객체에 있는 0~1사이의 난수들을 나타낸다.
여기에 10을 곱하면 Math의 범위가 0~10으로 바뀐다. (100을 곱하면 0~100사이의 난수)
즉 연산을 통해 범위를 바꿔줄 수 있다.
Math.floor()은 소수점을 내림 처리 하여 정수만 표현 할 수 있게 해준다.
*정수를 표현하는 3가지 방법
1)소수점 올림
Math.ceil()
2) 소수점 내림
Math.floor()
3) 소수점 반올림
Math.round()
2. if문
function random() {
return Math.floor(Math.random() * 10)}
const a = random()
if (a === 0) {
console.log('a는 0이다.')
} else if (a === 2) {
console.log('a는 2이다.')
}
else {
console.log('나머지 수')
}
조건 외의 나머지를 표시 할 때에는 else 부분에 입력한다.
3. Switch문
function random() {
return Math.floor(Math.random() * 10)}
const a = random()
switch (a) {
case 0:
console.log('a는 0이다')
break
case 2:
console.log('a는 2이다')
break
case 3:
console.log('a는 3이다.')
break
default:
}
if 문과 다르게 case로 조건을 걸고 break를 선언해서 조건문을 끝내줘야 한다.
else 대신 default를 사용해서 else를 표시한다. default에는 break를 입력하지 않아도 된다.( 마지막 문장이기 떄문에)