Create a unique number with javascript time

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

    in reference to #Marcelo Lazaroni solution above

    Date.now() + Math.random()
    

    returns a number such as this 1567507511939.4558 (limited to 4 decimals), and will give non-unique numbers (or collisions) every 0.1%.

    adding toString() fixes this

    Date.now() + Math.random().toString()

    returns '15675096840820.04510962122198503' (a string), and is further so 'slow' that you never get the 'same' millisecond, anyway.

提交回复
热议问题