JavaScript
JavaScript* 조건 연산자 조건문 조건조건
해보구
2024. 3. 22. 17:10
반응형
랜덤 정수를 생성하고 조건에 따라 메세지 나오게하기
/*
랜덤 정수 생성하기 : Math.random()
1이상 10이하의 랜덤 정수 생성
Math.random() - 0.0 <= ~ < 1.0
Math.random() * 10 - 0.0 <= ~ < 10.0
Math.floor() : 소수점이하 버림
Math.floor(9.389) => 9
Math.floor(Math.random() * 10); - 0 <= ~ < 10
Math.floor(Math.random() * 10) + 1; - 1 <= ~ < 11
// 랜덤 범위 정수값 공식
x이상 y이하의 랜덤정수 생성
Math.floor(Math.random() * (y - x + 1)) + x
# 117 ~ 142
Math.floor(Math.random() * (142 - 117 + 1)) + 117
Math.floor(Math.random() * 26)) + 117
*/
var randomNumber = Math.floor(Math.random() * 10) + 1;
console.log(`랜덤값: ${randomNumber}`);
var score = Math.floor(Math.random() * 101);
console.log(`점수: ${score}점`);
// var score = 60;
// console.log(`점수: ${score}점`);
if (score >= 60) {
console.log('합격하셨어요');
console.log('수고')
} else {
console.log(`불합격~~`);
}
if 뒤에는 반드시 () 괄호가 와야한다!
prompt는 string type 이기 때문에 앞에 +를 붙여야 숫자를 인식한다.
a === b === c 가 있을 때
(b에서는 true) 상태임
var money = 3000;
var food = (money >= 8000) ? '돈까스' : '라면';
var food;
if ( money >= 8000) {
food = '돈까스';
} else {
food = '라면';
}
console.log(`선택한 음식: ${food}`);
// 삼항연산자 ///
var food = (money >= 8000) ? '돈까스' : (money >= 5000) ? '쫄면' : '라면';
// 복잡할때는 아래식으로
var food;
if (money >= 8000) {
food = '돈까스';
} else if (money >= 5000) {
food = '쫄면';
} else if (money >= 3000) {
food = '라면';
} else {
food = '굶어';
}
한줄로 할 수있는 장점이 있지만 다중 조건일 경우에는 if문을 사용하는 법이 좋다.
반응형