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

วิธีสุ่มตัวเลข 1 ถึง 200 ใน JavaScript

ใช้ Math.random() ร่วมกับ Math.floor() สูตรมาตรฐานสำหรับช่วง Min ถึง Max (Inclusive)

สูตร

Math.floor(Math.random() * (max - min + 1)) + min

สำหรับ 1 ถึง 200: Math.floor(Math.random() * 200) + 1

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

<!DOCTYPE html>
<html>
  <body>
    <script>
      document.write(Math.floor(Math.random() * 200) + 1);
    </script>
  </body>
</html>

การทำงานขั้นตอน

  1. Math.random() → 0 ≤ x < 1
  2. * 200 → 0 ≤ x < 200
  3. Math.floor() → 0 ถึง 199
  4. + 1 → 1 ถึง 200

ฟังก์ชันสำเร็จรูป

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// ใช้งาน
getRandomIntInclusive(1, 200); // 1-200
getRandomIntInclusive(10, 50); // 10-50

หมายเหตุ: ไม่เหมาะสำหรับ Cryptography ใช้ crypto.getRandomValues(new Uint32Array(1))[0] % (max - min + 1) + min แทน