在JavaScript中生成兩個數字之間的隨機數

有沒有辦法在JavaScript中生成指定範圍(例如1到6:一、二、三、四、5或6)內的隨機數? 網絡


#1樓

數學不是個人強項,可是我一直在從事一個項目,我須要在正負之間生成不少隨機數。 dom

function randomBetween(min, max) {
    if (min < 0) {
        return min + Math.random() * (Math.abs(min)+max);
    }else {
        return min + Math.random() * max;
    }
}

例如 編碼

randomBetween(-10,15)//or..
randomBetween(10,20)//or...
randomBetween(-200,-100)

固然,您也能夠添加一些驗證,以確保除了數字之外不要使用其餘任何方法。 還要確保最小值始終小於或等於最大值。 spa


#2樓

我發現上面的Francisc解決方案沒有在結果中包含最小或最大數,所以我將其更改成: code

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

#3樓

Math.random()

Mozilla開發人員網絡文檔中: ip

// Returns a random integer between min (include) and max (include)

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

有用的例子: ci

// 0 -> 10
Math.floor(Math.random() * 11);

// 1 -> 10
Math.floor(Math.random() * 10) + 1;

// 5 -> 20
Math.floor(Math.random() * 16) + 5;

// -10 -> (-2)
Math.floor(Math.random() * 9) - 10;

#4樓

我正在搜索用TypeScript編寫的隨機數生成器,並在閱讀全部答案後編寫了此代碼,但願它適用於TypeScript編碼人員。 開發

Rand(min: number, max: number): number {
        return (Math.random() * (max - min + 1) | 0) + min;
    }

#5樓

或者,在下劃線 文檔

_.random(min, max)
相關文章
相關標籤/搜索