myk*_*hal 57
为什么不从Math.random()字符串表示中提取数字?
Math.random().toString().slice(2,11);
/*
Math.random()                         ->  0.12345678901234
             .toString()              -> "0.12345678901234"
                        .slice(2,11)  ->   "123456789"
 */
(要求是每个javascript实现Math.random()的精度至少为9位小数)
小智 52
您可以生成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;
}
或使用此内联"技巧"填充.
小智 20
也...
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万次迭代:~626ms.到目前为止最快 - parseInt是一个本机函数vs再次调用Math库.注意:见下文.
Math.floor(Math.random()*1000000000)
100万次迭代:~1005ms.两个函数调用.
String(Math.random()).substring(2,11)
100万次迭代:~2997ms.三个函数调用.
并且...
parseInt(Math.random()*1000000000)
100万次迭代:~362ms.注意:parseInt通常被认为是不安全的,没有radix参数.请参阅https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt或google"JavaScript:The Good Parts".但是,传递给parseInt的参数似乎永远不会以'0'或'0x'开头,因为输入首先乘以1000000000.YMMV.
Math.random().toFixed(length).split('.')[1]
使用 toFixed 允许您设置比默认值更长的长度(似乎在小数点后生成 15-16 位数字。如果需要,ToFixed 将让您获得更多数字。
在一行中:
var len = 10;
parseInt((Math.random() * 9 + 1) * Math.pow(10,len-1), 10);
脚步:
1 ? x < 10。Math.pow(10,len-1)(长度为的数字len)。parseInt()删除小数。| 归档时间: | 
 | 
| 查看次数: | 63235 次 | 
| 最近记录: |