javascript/jquery 中的uniqid()?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我一直在使用这个...
我使用它就像在 PHP 中使用它一样。两者返回相同的结果。
I have been using this...
I use it exactly as I would if it where PHP. Both return the same result.
试试这个(在 php 中工作)。
尝试一下 JavaScript::
Try this (Work in php).
Try this for JavaScript::
这里的所有答案(除了 phpjs)都不会生成唯一的 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 :
It's easy to add dynamic prefix if it's needed. Just change
unique_id_counter
into an array storing counters for each prefixes.虽然有点复杂,但我相信您已经明白要点了!
示例: http://jsfiddle.net/Ng4tB/
It's a bit convoluted, but you get the gist I'm sure!
Example: http://jsfiddle.net/Ng4tB/
真正的问题是,您是否需要 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.
它是按照与 PHP 的 uniqId() “相同”原理生成的 - 特别以微秒为单位的编码时间。
it is generated on "the same" priciple as PHP's uniqId() - specifically encoded time in microseconds.
Underscore.js 有一个
uniqueid()
方法https://underscorejs.org/#uniqueId
Underscore.js has a
uniqueid()
methodhttps://underscorejs.org/#uniqueId
找到这个:
https://github.com/makeable /uuid-v4.js/blob/master/uuid-v4.js
并对此稍加修改:
效果很好。
Found this:
https://github.com/makeable/uuid-v4.js/blob/master/uuid-v4.js
and slightly modified to this:
works great.