JavaScript 隨機數產生

今天要執行一個定時任務,但又不希望所有定時任務均在同一個時刻觸發。
我大概想要下面這樣的一個東西,希望定時任務在凌晨2點某一個分鐘觸發。

    const min = Utils.getRandomInt(60);
    const time = `0 ${min} 02 * * *`;

這裏就需要一個獲取隨機數的方式:

提供了三個函數
getRandomInt(max): 獲取小於某個值的整數隨機數
getRandomInt1(min, max): 獲取小於某值 大於等於某值的整數隨機數
getRandomIntInclusive(min, max): 獲取小於等於某值 大於等於某值的整數隨機數

function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}
console.log(getRandomInt(3));
// expected output: 0, 1 or 2
console.log(getRandomInt(1));
// expected output: 0
console.log(Math.random());
// expected output: 0~1 (0<= number <1)
console.log(getRandomInt(10));
// expected output: 0~1 (0<= number <9)


function getRandomInt1(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive
}

console.log(getRandomInt1(10, 30));
// expected output: (10<= number <30)

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive 
}

console.log(getRandomIntInclusive(10, 11));
// expected output: (10<= number <=11)


涉及到的函數:

Math.random()
//在0(包括)和1(不包括)之間的浮點僞隨機數。
Math.floor(x);
//對 x 進行下舍入,即向下取整。
Math.ceil(x)
//對數x進行上舍入,即向上取整。

注意JavaScript Number類型的邊界

參考:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章