JavaScript 랜덤 값 생성 방법
JavaScript에서 랜덤 값을 생성하는 다양한 방법을 정리했습니다.
1. 0 이상 1 미만의 랜덤 값
let randomValue = Math.random();
console.log(randomValue); // 0 이상 1 미만의 실수
2. 정수 범위 내 랜덤 값
let randomInt = Math.floor(Math.random() * 11);
console.log(randomInt); // 0 이상 10 이하의 정수
3. 특정 범위 내 랜덤 값 (min ~ max)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(5, 15)); // 5 이상 15 이하의 정수
4. 배열에서 랜덤한 요소 선택
let items = ["사과", "바나나", "체리", "포도"];
let randomItem = items[Math.floor(Math.random() * items.length)];
console.log(randomItem); // 배열 요소 중 하나 랜덤 선택
5. 랜덤한 Boolean 값
let randomBool = Math.random() < 0.5; // true 또는 false
console.log(randomBool);
6. 랜덤한 색상 코드 (Hex)
function getRandomColor() {
return '#' + Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0');
}
console.log(getRandomColor()); // 예: #a3e12f
이제 JavaScript에서 다양한 랜덤 값을 생성하는 방법을 쉽게 활용할 수 있습니다!
'프로그램 코딩 > JavaScript | HTML5' 카테고리의 다른 글
[JavaScript] 진동(vibrate) 처리 (0) | 2025.02.12 |
---|---|
자주 사용하는 내장 객체 (Array, Object, String 등) (0) | 2025.02.10 |
이벤트와 DOM 조작 (0) | 2025.02.10 |
함수 기초 (함수 선언, 호출, 매개변수) (0) | 2025.02.10 |
제어문 (조건문과 반복문) (0) | 2025.02.10 |