Javascript时间戳号不是唯一的 [英] Javascript timestamp number is not unique
问题描述
我需要生成一个唯一的号码才能在我的代码中使用。我使用
I need a unique number to be generated to be used in my code.I use
var id = new Date().valueOf()
我知道上面的返回毫秒数。
但值不是唯一的。例如: 1385035174752 。这个数字生成两次或更多。
I know the above returns the number of milliseconds. But the values are not unique.For example :1385035174752.This number is generated twice or more than that.
我的问题是为什么它不是唯一的?如何从当前日期/时间获得唯一编号?
My question is Why is it not unique? and how do i get unique number from current date/time?
推荐答案
如果您需要唯一性,请使用 Math.random()
,不任何 Date()
API。
If you need uniqueness, use Math.random()
, and not any of the Date()
APIs.
Math.random
返回0到1之间的整数。如果你真的想要一个基于当前时间的半唯一数字,你可以将 Date
API与 Math.random
结合使用。 例如:
Math.random
returns an integer between and including 0 and 1. If you really want an semi-unique number based on the current time, you can combine the Date
API with Math.random
. For example:
var id = new Date().getTime() + Math.random();
在现代浏览器中,您还可以使用 performance.now()
。此API保证每个新调用的返回值都是唯一的。
In modern browsers, you can also use performance.now()
. This API guarantees that every new call's return value is unique.
这篇关于Javascript时间戳号不是唯一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!