Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

สุ่มตัวเลขในช่วงที่กำหนดด้วย Math.random() ใน JavaScript

สูตร: Math.floor(Math.random() * (max - min + 1)) + min

ตัวอย่างโค้ด

function getRandomValueBetweenTwoValues(startRange, endRange) {
    return Math.floor(Math.random() * (endRange - startRange + 1) + startRange);
}

console.log(getRandomValueBetweenTwoValues(400, 480));

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo109.js)

ผลลัพธ์ตัวอย่าง

401

(ผลลัพธ์จะสุ่มทุกครั้งที่รัน)