javascript/jquery 中的uniqid()?

发布于 2024-10-15 14:58:49 字数 239 浏览 3 评论 0原文

javascript中这个函数的等价物是什么:

http://php.net/manual/en/ function.uniqid.php

基本上我需要生成一个随机ID,如下所示:a4245f54345并以字母字符开头(这样我可以将其用作CSS id)

what's the equivalent of this function in javascript:

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

风渺 2024-10-22 14:58:49

我一直在使用这个...

我使用它就像在 PHP 中使用它一样。两者返回相同的结果。

function uniqid(prefix = "", random = false) {
    const sec = Date.now() * 1000 + Math.random() * 1000;
    const id = sec.toString(16).replace(/\./g, "").padEnd(14, "0");
    return `${prefix}${id}${random ? `.${Math.trunc(Math.random() * 100000000)}`:""}`;
};

I have been using this...

I use it exactly as I would if it where PHP. Both return the same result.

function uniqid(prefix = "", random = false) {
    const sec = Date.now() * 1000 + Math.random() * 1000;
    const id = sec.toString(16).replace(/\./g, "").padEnd(14, "0");
    return `${prefix}${id}${random ? `.${Math.trunc(Math.random() * 100000000)}`:""}`;
};
大姐,你呐 2024-10-22 14:58:49

试试这个(在 php 中工作)。

$prefix = chr(rand(97,121));  
$uniqid =  $prefix.uniqid(); // $uniqid = uniqid($prefix);

尝试一下 JavaScript::

var n = Math.floor(Math.random() * 11);
var k = Math.floor(Math.random() * 1000000);
var m = String.fromCharCode(n) + k;

Try this (Work in php).

$prefix = chr(rand(97,121));  
$uniqid =  $prefix.uniqid(); // $uniqid = uniqid($prefix);

Try this for JavaScript::

var n = Math.floor(Math.random() * 11);
var k = Math.floor(Math.random() * 1000000);
var m = String.fromCharCode(n) + k;
尝蛊 2024-10-22 14:58:49

这里的所有答案(除了 phpjs)都不会生成唯一的 ID,因为它是基于随机的。随机并不唯一!

一个简单的解决方案:

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 ;
        }
    }
}

如果需要,可以轻松添加动态前缀。只需将 unique_id_counter 更改为存储每个前缀的计数器的数组即可。

All answers here (except phpjs) don't generate unique IDs because it's based on random. Random is not unique !

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.

不羁少年 2024-10-22 14:58:49
<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>

虽然有点复杂,但我相信您已经明白要点了!
示例: http://jsfiddle.net/Ng4tB/

<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/

愛上了 2024-10-22 14:58:49

真正的问题是,您是否需要 UUID 符合 RFC 4122?你的问题似乎表明你不这样做,所以简单地创建一个基于 Math.random() 的函数来生成这样的 ID 并不会太难。而且它会比 phpJS 实现快很多。

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.

背叛残局 2024-10-22 14:58:49
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;
}

它是按照与 PHP 的 uniqId() “相同”原理生成的 - 特别以微秒为单位的编码时间。

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.

隐诗 2024-10-22 14:58:49

Underscore.js 有一个 uniqueid() 方法
https://underscorejs.org/#uniqueId

_.uniqueId([前缀])
为需要的客户端模型或 DOM 元素生成一个全局唯一的 id。如果传递了前缀,则 id 将附加到其上。

_.uniqueId('contact_');  
=> '联系_104'

Underscore.js has a uniqueid() method
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'
埋情葬爱 2024-10-22 14:58:49

找到这个:

https://github.com/makeable /uuid-v4.js/blob/master/uuid-v4.js

并对此稍加修改:

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;
}

效果很好。

Found this:

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文