Create a unique number with javascript time

后端 未结 30 3065
生来不讨喜
生来不讨喜 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:47

    To get a unique number:

    function getUnique(){
        return new Date().getTime().toString() + window.crypto.getRandomValues(new Uint32Array(1))[0];
    }
    // or 
    function getUniqueNumber(){
        const now = new Date();
        return Number([
            now.getFullYear(),
            now.getMonth(),
            now.getDate(),
            now.getHours(),
            now.getMinutes(),
            now.getUTCMilliseconds(),
            window.crypto.getRandomValues(new Uint8Array(1))[0]
        ].join(""));
    }
    

    Example:

    getUnique()
    "15951973277543340653840"
    
    for (let i=0; i<5; i++){
        console.log( getUnique() );
    }
    15951974746301197061197
    15951974746301600673248
    15951974746302690320798
    15951974746313778184640
    1595197474631922766030
    
    getUniqueNumber()
    20206201121832230
    
    for (let i=0; i<5; i++){
        console.log( getUniqueNumber() );
    }
    2020620112149367
    2020620112149336
    20206201121493240
    20206201121493150
    20206201121494200
    

    you can change the length using:

    new Uint8Array(1)[0]
    // or
    new Uint16Array(1)[0]
    // or
    new Uint32Array(1)[0]
    

提交回复
热议问题