JavaScript實現(xiàn)隨機產生字符串的方法分享
這個東西就是隨機產生字符串的函數(shù)。
參數(shù),代碼里面有解釋。
用途:當作產生隨機密碼來看使用吧,或者nodejs后端存儲數(shù)據(jù)庫的主鍵來使用吧。
/**
* 這個是一個隨機產生字符串的函數(shù)
* @param {object} cfg 參數(shù)
cfg = {
split: '', // 分割字符
splitNum: 0, // 分隔個數(shù)
num: 16, // 產生隨機字符個數(shù) 默認16
char: 'dAa', // d數(shù)字 A大寫的字符 a小寫的字符 默認dAa
append: '@*!+-=*&[()`?.]', // 添加的其他額外字符,支持數(shù)組[]和字符串 默認@*!+-=*&[()`?.
ignore: '', // 可以忽略的字符,支持數(shù)組[]和字符串 優(yōu)先級最高
}
* @returns 返回隨機字符串
*/
const rand_str = (cfg) => {
if(cfg === undefined) cfg = {}
const getValue = (s, d) => {
if([undefined, null].includes(s)) return d
else return s
}
cfg = {
split: getValue(cfg.split, ''), // 分割字符
splitNum: parseInt(cfg.splitNum) || 0, // 分隔個數(shù)
num: parseInt(cfg.num) || 16, // 字符個數(shù) 默認16
char: getValue(cfg.char, 'dAa') , // d數(shù)字 A大寫的字符 a小寫的字符
append: getValue(cfg.append, '@*!+-=*&[()`?.') , // 支持數(shù)組[]和字符串 一般指特殊字符@*!+-=*&[()`?.
ignore: getValue(cfg.ignore, '') // 支持數(shù)組[]和字符串 優(yōu)先級最高
}
// console.log(cfg)
let set = new Set()
const getChars = (str) => {
for(const s of str) set.add(s)
}
// 1、先取出append特殊字符的編碼
getChars(cfg.append)
// 2、獲取char中的字符集
const number = "0123456789"
const bigChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const smallChars = "abcdefghijklmnopqrstuvwxyz"
for(const s of cfg.char) {
if(s === 'd') getChars(number)
else if (s === 'A') getChars(bigChars)
else if (s === 'a') getChars(smallChars)
// 其他的字符 自動忽略
}
// 3. 排除ignore忽略的元素
for(const s of cfg.ignore) set.delete(s)
// 4. 生成數(shù)組
const arr = Array.from(set)
// console.log(arr)
// 5. 打亂集合
const swap = (firstIndex, secondIdex) => {
const t = arr[firstIndex]
arr[firstIndex] = arr[secondIdex]
arr[secondIdex] = t
}
const size = arr.length
for(let i = 0; i < cfg.num; i++) swap(Math.floor(Math.random() * size), Math.floor(Math.random() * size))
// 6、生成隨機字符串
let re = ""
for(let i = 0; i < cfg.num; i++) {
if(i % cfg.splitNum === 0 && i !== 0) re += cfg.split
re += arr[Math.floor(Math.random() * size)]
}
return re
}
/**
* 測試
*/
for(let i = 1; i< 10; i++) console.log(rand_str())
console.log('----------------------------')
const config = {
split: '', // 分割字符
splitNum: 0, // 分隔個數(shù)
num: 20, // 產生隨機字符個數(shù) 默認16
char: 'Aa', // d數(shù)字 A大寫的字符 a小寫的字符 默認dAa
append: '@*!+-=*&[()`?.]', // 添加的其他額外字符,支持數(shù)組[]和字符串 默認@*!+-=*&[()`?.
ignore: '@*!+-=*&[()`?.]', // 可以忽略的字符,支持數(shù)組[]和字符串 優(yōu)先級最高
}
for(let i = 1; i< 10; i++) console.log(rand_str(config))
知識點補充
math.random()
math.random()方法返回一個偽隨機浮點數(shù),結果區(qū)間為[0, 1),在區(qū)間內近似均勻分布,可以使用別的方法縮放到所需的范圍。它實現(xiàn)了選擇初始值的隨機數(shù)生成算法;使用者無法主動選擇值或進行重置。
Math.random(); // 0.21446359414239313
Math.random 會提供給我們一個[0,1)之間的隨機數(shù),但是如果我們要[1,10]范圍隨機整數(shù)的話,可以使用以下三個函數(shù):
- math.round() 四舍五入
- math.ceil() 向上取整
- math.floor() 向下取整
Math.ceil(Math.random() * 10); // 7
快速生成隨機字符串
利用 toString,hex 代表進制,最大不能超過 36,36 = 10 + 26 個英文字母 hex 越大,字母占比越多
Math.random().toString(36).slice(2);
注意:
- 該方式無法保證字符串長度一致
- 當 Math.random()的結果是有限長度小數(shù)時,比如 0.5,0.55,會導致得到的結果不符合預期
測試
// 十萬次
var a = Array.from(new Array(100000).keys());
var b = a.map((i) => Math.random().toString(36).slice(2));
new Set(Object.values(b.map((i) => i.length)));
// Set(8) {10, 11, 9, 12, 8, 13, 14, 7}
可以自己試一下,每次運行的結果可能是不同的,其原因是 Math.random()生成的數(shù)字保留的小數(shù)長度本身是不固定的
// 百萬次
var a = Array.from(new Array(1000000).keys());
new Set(Object.values(a.map((i) => (Math.random() + "").length)));
// Set(14) {19, 18, 17, 20, 16, 21, 22, 15, 14, 13, 23, 11, 24, 12}
快速生成固定長度的隨機字符串
/**
* 生成指定長度的字符串
* @param {Number} hex 代表進制,取值范圍[2 - 36],最大不能超過 36, 數(shù)字越大字母占比越高,小于11為全數(shù)字
* @param {Number} len 字符串長度
*/
function generateStr(hex, len) {
if (hex < 2 || hex > 36) {
throw new RangeError("hex argument must be between 2 and 36");
}
var res = Math.random().toString(hex).slice(2);
var resLen = res.length;
while (resLen < len) {
res += Math.random().toString(hex).slice(2);
resLen = res.length;
}
return res.substr(0, len);
}
測試
// 執(zhí)行十萬次,可以在50ms左右穩(wěn)定獲取長度為10的隨機字符串
console.time("exec");
var a = Array.from(new Array(100000).keys());
console.log(new Set(a.map((i) => generateStr(22, 10).length)));
console.timeEnd("exec");
// Set(1) {10}
// exec: 49.966064453125 ms到此這篇關于JavaScript實現(xiàn)隨機產生字符串的方法分享的文章就介紹到這了,更多相關JavaScript隨機產生字符串內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- js隨機生成字母數(shù)字組合的字符串 隨機動畫數(shù)字
- Js生成隨機數(shù)/隨機字符串的方法小結【5種方法】
- JS實現(xiàn)生成由字母與數(shù)字組合的隨機字符串功能詳解
- JS簡單生成由字母數(shù)字組合隨機字符串示例
- javascript創(chuàng)建含數(shù)字字母的隨機字符串方法總結
- JavaScript生成隨機字符串的方法
- javascript自動生成包含數(shù)字與字符的隨機字符串
- JS生成隨機字符串的多種方法
- js 數(shù)組隨機字符串(廣告不重復)
- js 按照指定間隔 向字符串中插入隨機字符串的實現(xiàn)代碼
- JS實現(xiàn)隨機生成字符串(可指定長度)的示例代碼
相關文章
JavaScript自定義localStorage監(jiān)聽事件的解決方法
在項目開發(fā)過程中,發(fā)現(xiàn)有很多時候進行l(wèi)ocalStorage.setItem()操作設置本地存儲后,頁面必須刷新才能夠獲取到存儲數(shù)據(jù),為了解決這個問題,就必須要用到自定義localStorage監(jiān)聽事件了,所以本文給大家介紹了自定義localStorage監(jiān)聽事件,需要的朋友可以參考下2024-10-10
js實現(xiàn)微信/QQ直接跳轉到支付寶APP打開口令領紅包功能
最近支付寶的領紅包可真是刷爆了各個微信群啊,滿群都是支付寶口令,可是這樣推廣很麻煩,下面小編給大家?guī)砹薺s實現(xiàn)微信/QQ直接跳轉到支付寶APP打開口令領紅包功能,需要的朋友參考下2018-01-01
document.getElementById方法在Firefox與IE中的區(qū)別
相信很多朋友在寫JavaScript的時候,對瀏覽器的兼容問題會感到很頭疼。這不,煩什么,什么就來了,特記錄下來,與大家分享。2010-05-05

