在JavaScript中生成一个随机的字母数字(大写,小写和数字)字符串来用作可能唯一的标识符的最短方法是什么?
当前回答
可以使用lodash uniqueId:
_.uniqueId([prefix=''])
生成唯一的ID。如果给出了prefix,则ID被追加到它后面。
其他回答
使用md5库:https://github.com/blueimp/JavaScript-MD5
最短的方法:
md5(随机数学。()
如果你想限制大小为5:
md5 (math . random())。substr (0, 5)
或者根据Jar Jar的建议,这是我在最近的一个项目中使用的方法(以克服长度限制):
var randomString = function (len, bits)
{
bits = bits || 36;
var outStr = "", newStr;
while (outStr.length < len)
{
newStr = Math.random().toString(bits).slice(2);
outStr += newStr.slice(0, Math.min(newStr.length, (len - outStr.length)));
}
return outStr.toUpperCase();
};
Use:
randomString(12, 16); // 12 hexadecimal characters
randomString(200); // 200 alphanumeric characters
我只是发现了一个非常好的优雅的解决方案:
Math.random().toString(36).slice(2)
这个实现的注意事项:
This will produce a string anywhere between zero and 12 characters long, usually 11 characters, due to the fact that floating point stringification removes trailing zeros. It won't generate capital letters, only lower-case and numbers. Because the randomness comes from Math.random(), the output may be predictable and therefore not necessarily unique. Even assuming an ideal implementation, the output has at most 52 bits of entropy, which means you can expect a duplicate after around 70M strings generated.
var randomString = function(length) {
var str = '';
var chars ='0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split(
'');
var charsLen = chars.length;
if (!length) {
length = ~~(Math.random() * charsLen);
}
for (var i = 0; i < length; i++) {
str += chars[~~(Math.random() * charsLen)];
}
return str;
};
beans建议的另一种答案变体
(Math.random()*1e32).toString(36)
通过改变乘数1e32,你可以改变随机字符串的长度。
推荐文章
- 在数组中获取所有选中的复选框
- 如何为Firebase构建云函数,以便从多个文件部署多个函数?
- 如何发送推送通知到web浏览器?
- AngularJS:工厂和服务?
- js:将一个组件包装成另一个组件
- 父ng-repeat从子ng-repeat的访问索引
- JSHint和jQuery: '$'没有定义
- 模仿JavaScript中的集合?
- 用JavaScript验证电话号码
- 如何在HTML5中改变视频的播放速度?
- 谷歌地图API v3:我可以setZoom后fitBounds?
- ES6/2015中的null安全属性访问(和条件赋值)
- 与push()相反;
- JS字符串“+”vs concat方法
- AngularJS使用ng-class切换类