语法 类和对象 字符串 数组 日期和时间 数学 方法 元编程 jQuery Ajax 正则表达式 网络 设计模式 数据库 测试

发布于 2016-05-29 08:13:12 | 129 次阅读 | 评论: 0 | 来源: 网络整理

问题

你想随机生成一个唯一的标识符。

解决方案

可以根据一个随机数值生成一个 Base 36 编码的字符串。

uniqueId = (length=8) ->
  id = ""
  id += Math.random().toString(36).substr(2) while id.length < length
  id.substr 0, length

uniqueId()    # => n5yjla3b
uniqueId(2)   # => 0d
uniqueId(20)  # => ox9eo7rt3ej0pb9kqlke
uniqueId(40)  # => xu2vo4xjn4g0t3xr74zmndshrqlivn291d584alj

讨论

使用其他技术也可以,但这种方法相对来说性能更高,也更灵活。

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务