1

我正在尝试生成固定长度的随机数(长度为 9)。但是我的代码有时会打印 8 个长度的随机数,有时会打印 9 个长度的随机数。

是我正在尝试做的,但采用不同的方法(我已将其修改为固定的随机数长度)

当我将长度作为 9 作为参数传递时,我无法理解为什么它打印长度为 8 的随机数?

如果有人能说出为什么会这样,那就太好了。

下面是完整的 Nodejs 代码

var last_nonce = null;
var nonce_incr = null;
// if you call new Date to fast it will generate
// the same ms, helper to make sure the nonce is
// truly unique (supports up to 999 calls per ms).
module.exports = {
    getNonce: function(length) {
        if (length === undefined || !length) {
            length = 8;
        }
        var MOD = Math.pow(10, length);
        var now = (+new Date());
        if (now !== last_nonce) {
            nonce_incr = -1;
        }
        nonce_incr++;
        last_nonce = now;
        var nonce_multiplier = ((nonce_incr < 10) ? 10 : ((nonce_incr < 100) ? 100 : 1000));
        var s = (((now % MOD) * nonce_multiplier) + nonce_incr) % MOD;
        return s;
    }
}
//test code
if(require.main === module) {
    console.time("run time");
    //importing async module
    var async = require('async');
    var arr = [];
    //generating 1000 length array to use it in making 1000 async calls
    //to getNonce function
    for(var i=0; i<1000; i++) arr.push(i);
    //this will call getNonce function 1000 time parallely
    async.eachLimit(arr, 1000, function(item, cb) {
        console.log(module.exports.getNonce(9));
        cb();
    }, function(err) {console.timeEnd("run time");});
}

样本输出:

708201864  --> nonce length 9
708201865
708201866
70820190   --> nonce length 8 (why it is coming 8?? when passed length is 9)
70820191
70820192
70820193
70820194
70820195
70820196
70820197
70820198
70820199
708201910
708201911
708201912
708201913
708201914
708201915
708201916
708201917
708201918
4

0 回答 0