javascript/jquery 中的 uniqid()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4872380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
uniqid() in javascript/jquery?
提问by Alex
what's the equivalent of this function in javascript:
javascript中这个函数的等价物是什么:
http://php.net/manual/en/function.uniqid.php
http://php.net/manual/en/function.uniqid.php
Basically I need to generate a random ID that looks like: a4245f54345
and starts with a alphabetic character (so I can use it as a CSS id)
基本上我需要生成一个随机 ID,看起来像:a4245f54345
并以字母字符开头(所以我可以将它用作 CSS id)
回答by Manish Trivedi
Try this (Work in php).
试试这个(在 php 中工作)。
$prefix = chr(rand(97,121));
$uniqid = $prefix.uniqid(); // $uniqid = uniqid($prefix);
Try this for JavaScript::
试试这个 JavaScript ::
var n = Math.floor(Math.random() * 11);
var k = Math.floor(Math.random() * 1000000);
var m = String.fromCharCode(n) + k;
回答by Josh Merlino
I have been using this ...
我一直在用这个...
I use it exactly as I would if it where PHP. Both return the same result.
我完全按照我在 PHP 中使用它的方式使用它。两者都返回相同的结果。
function uniqid(a = "",b = false){
var c = Date.now()/1000;
var d = c.toString(16).split(".").join("");
while(d.length < 14){
d += "0";
}
var e = "";
if(b){
e = ".";
var f = Math.round(Math.random()*100000000);
e += f;
}
return a + d + e;
}
回答by DylannCordel
All answers here (except phpjs) don't generate unique IDs because it's based on random. Random is not unique !
此处的所有答案(phpjs 除外)都不会生成唯一 ID,因为它基于随机。随机不是唯一的!
a simple solution :
一个简单的解决方案:
window.unique_id_counter = 0 ;
var uniqid = function(){
var id ;
while(true){
window.unique_id_counter++ ;
id = 'uids_myproject_' + window.unique_id_counter ;
if(!document.getElementById(id)){
/*you can remove the loop and getElementById check if you
are sure that noone use your prefix and ids with this
prefix are only generated with this function.*/
return id ;
}
}
}
It's easy to add dynamic prefix if it's needed. Just change unique_id_counter
into an array storing counters for each prefixes.
如果需要,可以很容易地添加动态前缀。只需更改unique_id_counter
为存储每个前缀的计数器的数组。
回答by Barrie Reader
<html>
<head>
<script type="text/javascript">
function generateSerial(len) {
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var string_length = 10;
var randomstring = '';
for (var x=0;x<string_length;x++) {
var letterOrNumber = Math.floor(Math.random() * 2);
if (letterOrNumber == 0) {
var newNum = Math.floor(Math.random() * 9);
randomstring += newNum;
} else {
var rnum = Math.floor(Math.random() * chars.length);
randomstring += chars.substring(rnum,rnum+1);
}
}
alert(randomstring);
}
generateSerial(8);
</script>
</head>
<body>
</body>
</html>
It's a bit convoluted, but you get the gist I'm sure!
Example:http://jsfiddle.net/Ng4tB/
这有点令人费解,但我相信你明白了要点!
示例:http : //jsfiddle.net/Ng4tB/
回答by Jens Roland
The real question is, do you need the UUID to be RFC 4122 compliant? Your question seems to suggest you don't, so it wouldn't be too hard to create a function based simply on Math.random() to generate IDs like that. Plus it will be a lot faster than the phpJS implementation.
真正的问题是,您是否需要 UUID 符合 RFC 4122?您的问题似乎表明您不这样做,因此仅基于 Math.random() 创建一个函数来生成这样的 ID 并不会太难。此外,它会比 phpJS 实现快得多。
回答by Brad Kent
Underscore.js has a uniqueid()
method
https://underscorejs.org/#uniqueId
Underscore.js 有一个uniqueid()
方法
https://underscorejs.org/#uniqueId
_.uniqueId([prefix])
Generate a globally-unique id for client-side models or DOM elements that need one. If prefix is passed, the id will be appended to it._.uniqueId('contact_'); => 'contact_104'
_.uniqueId([prefix])
为需要一个的客户端模型或 DOM 元素生成一个全局唯一的 id。如果前缀被传递,id 将被附加到它。_.uniqueId('contact_'); => 'contact_104'
回答by Luca Reghellin
Found this:
发现这个:
https://github.com/makeable/uuid-v4.js/blob/master/uuid-v4.js
https://github.com/makeable/uuid-v4.js/blob/master/uuid-v4.js
and slightly modified to this:
并稍微修改为:
function uniqid(length){
var dec2hex = [];
for (var i=0; i<=15; i++) {
dec2hex[i] = i.toString(16);
}
var uuid = '';
for (var i=1; i<=36; i++) {
if (i===9 || i===14 || i===19 || i===24) {
uuid += '-';
} else if (i===15) {
uuid += 4;
} else if (i===20) {
uuid += dec2hex[(Math.random()*4|0 + 8)];
} else {
uuid += dec2hex[(Math.random()*16|0)];
}
}
if(length) uuid = uuid.substring(0,length);
return uuid;
}
works great.
效果很好。
回答by kobliha
function uniqId(prefix) {
if (window.performance) {
var s = performance.timing.navigationStart;
var n = performance.now();
var base = Math.floor((s + Math.floor(n))/1000);
} else {
var n = new Date().getTime();
var base = Math.floor(n/1000);
}
var ext = Math.floor(n%1000*1000);
var now = ("00000000"+base.toString(16)).slice(-8)+("000000"+ext.toString(16)).slice(-5);
if (now <= window.my_las_uid) {
now = (parseInt(window.my_las_uid?window.my_las_uid:now, 16)+1).toString(16);
}
window.my_las_uid = now;
return (prefix?prefix:'')+now;
}
it is generated on "the same" priciple as PHP's uniqId() - specifically encoded time in microseconds.
它是按照与 PHP 的 uniqId() “相同”的原则生成的——特别是以微秒为单位的编码时间。