[英]JavaScript, Generate a Random Number that is 9 numbers in length
我正在尋找一種高效、優雅的方法來生成長度為 9 位的 JavaScript 變量:
示例:323760488
您可以生成 9 個隨機數字並將它們連接在一起。
或者,您可以調用random()
並將結果乘以 1000000000:
Math.floor(Math.random() * 1000000000);
由於Math.random()
生成一個介於 0 和 1 之間的隨機雙精度數,因此您將有足夠的精度位數以在最低有效位置仍然具有隨機性。
如果您想確保您的號碼以非零數字開頭,請嘗試:
Math.floor(100000000 + Math.random() * 900000000);
或者用零填充:
function LeftPadWithZeros(number, length)
{
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
或者使用這個內聯“技巧”填充。
為什么不從Math.random()
字符串表示中提取數字?
Math.random().toString().slice(2,11);
/*
Math.random() -> 0.12345678901234
.toString() -> "0.12345678901234"
.slice(2,11) -> "123456789"
*/
(要求是每個 javascript 實現Math.random()
的精度至少為 9 位小數)
還...
function getRandom(length) {
return Math.floor(Math.pow(10, length-1) + Math.random() * 9 * Math.pow(10, length-1));
}
getRandom(9) => 234664534
我找到的三種方法,按效率排序:(測試機運行Firefox 7.0 Win XP)
parseInt(Math.random()*1000000000, 10)
100 萬次迭代:~626 毫秒。 到目前為止最快的 - parseInt 是一個本地函數,而不是再次調用 Math 庫。 注意:見下文。
Math.floor(Math.random()*1000000000)
100 萬次迭代:~1005 毫秒。 兩個函數調用。
String(Math.random()).substring(2,11)
100 萬次迭代:~2997 毫秒。 三個函數調用。
並且...
parseInt(Math.random()*1000000000)
100 萬次迭代:~362 毫秒。 注意:parseInt 通常被認為在沒有基數參數的情況下使用是不安全的。 請參閱https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt或谷歌“JavaScript:好的部分”。 但是,傳遞給 parseInt 的參數似乎永遠不會以“0”或“0x”開頭,因為輸入首先乘以 1000000000。YMMV。
Math.random().toFixed(length).split('.')[1]
使用 toFixed 允許您設置比默認長度更長的長度(似乎在小數點后生成 15-16 位數字。如果需要,ToFixed 會讓您獲得更多數字。
在一行中(ish):
var len = 10;
parseInt((Math.random() * 9 + 1) * Math.pow(10,len-1), 10);
腳步:
1 ≤ x < 10
的隨機數。Math.pow(10,len-1)
(長度為len
的數字)。parseInt()
刪除小數。以為我會刺你的問題。 當我運行以下代碼時,它對我有用。
<script type="text/javascript">
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
} //The maximum is exclusive and the minimum is inclusive
$(document).ready(function() {
$("#random-button").on("click", function() {
var randomNumber = getRandomInt(100000000, 999999999);
$("#random-number").html(randomNumber);
});
</script>
這已經有足夠的答案了嗎?
我猜不會。 因此,即使Math.random()
決定返回類似0.000235436
的內容,這也應該可靠地提供一個 9 位數字:
Math.floor((Math.random() + Math.floor(Math.random()*9)+1) * Math.pow(10, 8))
屏幕抓取此頁面:
function rand(len){var x='';
for(var i=0;i<len;i++){x+=Math.floor(Math.random() * 10);}
return x;
}
rand(9);
var number = Math.floor(Math.random()*899999999 + 100000000)
如果你想生成隨機電話號碼,那么通常禁止它們以零開頭。 這就是為什么你應該結合幾種方法:
Math.floor(Math.random()*8+1)+Math.random().toString().slice(2,10);
這將在 100 000 000 到 999 999 999 之間隨機生成
使用其他方法時,我很難獲得可靠的結果,因為前導零在某種程度上是個問題。
我知道答案很舊,但我想分享這種生成從 0 到 n 的整數或浮點數的方法。 請注意,點(浮點數)的位置在邊界之間是隨機的。 該數字是一個字符串,因為現在 9007199254740991 的MAX_SAFE_INTEGER的限制
Math.hRandom = function(positions, float = false) { var number = ""; var point = -1; if (float) point = Math.floor(Math.random() * positions) + 1; for (let i = 0; i < positions; i++) { if (i == point) number += "."; number += Math.floor(Math.random() * 10); } return number; } //integer random number 9 numbers console.log(Math.hRandom(9)); //float random number from 0 to 9e1000 with 1000 numbers. console.log(Math.hRandom(1000, true));
function randomCod(){
let code = "";
let chars = 'abcdefghijlmnopqrstuvxwz';
let numbers = '0123456789';
let specialCaracter = '/{}$%&@*/()!-=?<>';
for(let i = 4; i > 1; i--){
let random = Math.floor(Math.random() * 99999).toString();
code += specialCaracter[random.substring(i, i-1)] + ((parseInt(random.substring(i, i-1)) % 2 == 0) ? (chars[random.substring(i, i-1)].toUpperCase()) : (chars[random.substring(i, i+1)])) + (numbers[random.substring(i, i-1)]);
}
code = (code.indexOf("undefined") > -1 || code.indexOf("NaN") > -1) ? randomCod() : code;
return code;
}
與max
互斥: Math.floor(Math.random() * max);
包含max
: Math.round(Math.random() * max);
為了生成長度為 n 的數字字符串,感謝@nvitaterna,我想到了這個:
1 + Math.floor(Math.random() * 9) + Math.random().toFixed(n - 1).split('.')[1]
它防止第一個數字為零。 每次調用它時,它都可以生成長度為 ~ 50 的字符串。
var number = Math.floor(Math.random() * 900000000) + 100000000
對於10 個字符
Math.floor(Math.random() * 9000000000) + 1000000000
來自https://gist.github.com/lpf23/9762508
此答案適用於希望生成10位數字(沒有國家代碼)的人
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.