Javascript时间戳编号不是唯一的

Javascript timestamp number is not unique(Javascript时间戳编号不是唯一的)
本文介绍了Javascript时间戳编号不是唯一的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要生成一个唯一编号以在我的代码中使用.我使用

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 之间的整数.如果你真的想要一个基于当前时间的半唯一数,你可以结合 <带有 Math.random 的代码>日期 API.例如:

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时间戳编号不是唯一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会
问题描述: 在javascript中引用js代码,然后导致反斜杠丢失,发现字符串中的所有\信息丢失。比如在js中引用input type=text onkeyup=value=value.replace(/[^\d]/g,) ,结果导致正则表达式中的\丢失。 问题原因: 该字符串含有\,javascript对字符串进行了转
Rails/Javascript: How to inject rails variables into (very) simple javascript(Rails/Javascript:如何将 rails 变量注入(非常)简单的 javascript)
CoffeeScript always returns in anonymous function(CoffeeScript 总是以匿名函数返回)
Ordinals in words javascript(javascript中的序数)
getFullYear returns year before on first day of year(getFullYear 在一年的第一天返回前一年)