search

Home  >  Q&A  >  body text

javascript - How to generate random auto-incrementing IDs

I want to use the auto-incremented id in URI to locate resources, but I don’t want the auto-incremented id to be used every time< code>+1, but I hope it is a random number as id, but this id is proportional.
What I think of so far One solution is to use timestamps. Is there any other solution?

Please indicate the programming language when answering

PHP中文网PHP中文网2798 days ago502

reply all(2)I'll reply

  • 淡淡烟草味

    淡淡烟草味2017-05-16 13:03:25

    JavaScript

    01

    Timestamp

    let id = + new Date(); 

    Another possible approach

    var R = (function(){
        var base = 0
          , inc  = 2;  
          
        // base 是基数, _inc 是增量 
        function config(_base, _inc){
            base = _base; 
            inc = _inc; 
        }
        
        function randGenerator(){
            var pre = base; 
            base += inc; 
            return pre + (Math.random() * inc); 
        }
        
        return {
            rand: randGenerator,
            config: config
        }
    })(); 
    
    R.config(0, 2); 
    R.rand(); // 0 ~ 2 中的随机数
    R.rand(); // 2 ~ 4 中的随机数 

    uuid

    https://www.npmjs.com/package...

    Use uuidV1

    reply
    0
  • 怪我咯

    怪我咯2017-05-16 13:03:25

    Generate a random number that does not repeat. Use

    •srand() - Seeds a random number generator
    •getrandmax() - Displays the largest possible value of a random number
    •mt_rand() - Generates better random numbers
    These three functions.

    reply
    0
  • Cancelreply