반응형
JavaScript 랜덤 값 생성 방법

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에서 다양한 랜덤 값을 생성하는 방법을 쉽게 활용할 수 있습니다!

728x90
반응형

+ Recent posts