Create a unique number with javascript time

后端 未结 30 2978
生来不讨喜
生来不讨喜 2020-12-02 08:31

I need to generate unique id numbers on the fly using javascript. In the past, I\'ve done this by creating a number using time. The number would be made up of the four digi

相关标签:
30条回答
  • 2020-12-02 08:37

    This can be achieved simply with the following code:

    var date = new Date();
    var components = [
        date.getYear(),
        date.getMonth(),
        date.getDate(),
        date.getHours(),
        date.getMinutes(),
        date.getSeconds(),
        date.getMilliseconds()
    ];
    
    var id = components.join("");
    
    0 讨论(0)
  • 2020-12-02 08:37

    This creates an almost guaranteed unique 32 character key client side, if you want just numbers change the "chars" var.

    var d = new Date().valueOf();
    var n = d.toString();
    var result = '';
    var length = 32;
    var p = 0;
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    
    for (var i = length; i > 0; --i){
        result += ((i & 1) && n.charAt(p) ? '<b>' + n.charAt(p) + '</b>' : chars[Math.floor(Math.random() * chars.length)]);
        if(i & 1) p++;
    };
    

    https://jsfiddle.net/j0evrdf1/1/

    0 讨论(0)
  • 2020-12-02 08:38

    Posting this code snippet here for my own future reference (not guaranteed but satisfactory "unique" enough):

    // a valid floating number
    window.generateUniqueNumber = function() {
        return new Date().valueOf() + Math.random();
    };
    
    // a valid HTML id
    window.generateUniqueId = function() {
        return "_" + new Date().valueOf() + Math.random().toFixed(16).substring(2);
    };
    
    0 讨论(0)
  • 2020-12-02 08:38

    I have done this way

    function uniqeId() {
       var ranDom = Math.floor(new Date().valueOf() * Math.random())
       return _.uniqueId(ranDom);
    }
    
    0 讨论(0)
  • 2020-12-02 08:40

    In ES6:

    const ID_LENGTH = 36
    const START_LETTERS_ASCII = 97 // Use 64 for uppercase
    const ALPHABET_LENGTH = 26
    
    const uniqueID = () => [...new Array(ID_LENGTH)]
      .map(() => String.fromCharCode(START_LETTERS_ASCII + Math.random() * ALPHABET_LENGTH))
     .join('')
    

    Example:

     > uniqueID()
     > "bxppcnanpuxzpyewttifptbklkurvvetigra"
    
    0 讨论(0)
  • 2020-12-02 08:43

    A better approach would be:

    new Date().valueOf();
    

    instead of

    new Date().getUTCMilliseconds();
    

    valueOf() is "most likely" a unique number. http://www.w3schools.com/jsref/jsref_valueof_date.asp.

    0 讨论(0)
提交回复
热议问题