代码细节
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| function radom_num(min, max) { if (typeof min !== 'number' || typeof max !== 'number') throw new Error('param invalidate,should be a number') if (min > max) { [min, max] = [max, min] } if (min === max) { return min } return Math.floor(Math.random() * (max - min + 1)) + min }
function ramdom_str(length = 6) { var str = 'abcdefghijklmnopqrstuvwxyz' str += str.toUpperCase(); str += '0123456789' var _str = '' for (let i = 0; i < length; i++) { var rand = Math.floor(Math.random() * str.length) _str += str[rand]; }
return _str }
|
库
另外,我是用 TypeScript 写了兼容浏览器端和服务器端的随机数获取库,直接使用npm i -S random.ts
安装即可,如下是使用方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import { getNum, getStr, getSafer } from 'random.ts' import * as Random from 'random.ts'
var Random = require('random.ts')
Random.getNum(2, 100)
Random.getNum("string", "string")
Random.getNum(0, 2 ** 53)
Random.getStr(6)
Random.getSafer()
|