欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript實現(xiàn)隨機產(chǎn)生字符串的方法分享

 更新時間:2022年11月29日 10:54:46   作者:KjPrime  
這篇文章主要為大家詳細介紹了JavaScript中實現(xiàn)隨機產(chǎn)生字符串的方法,文中的示例代碼簡潔易懂,對我們學習JavaScript有一定的幫助,需要的可以參考一下

這個東西就是隨機產(chǎn)生字符串的函數(shù)。

參數(shù),代碼里面有解釋。

用途:當作產(chǎn)生隨機密碼來看使用吧,或者nodejs后端存儲數(shù)據(jù)庫的主鍵來使用吧。

/**
 * 這個是一個隨機產(chǎn)生字符串的函數(shù)
 * @param {object} cfg 參數(shù)
    cfg = {
        split:  '',                 // 分割字符 
        splitNum: 0,                // 分隔個數(shù)
        num: 16,                    // 產(chǎn)生隨機字符個數(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,                    // 產(chǎn)生隨機字符個數(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ù),結(jié)果區(qū)間為[0, 1),在區(qū)間內(nèi)近似均勻分布,可以使用別的方法縮放到所需的范圍。它實現(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()的結(jié)果是有限長度小數(shù)時,比如 0.5,0.55,會導致得到的結(jié)果不符合預期

測試

// 十萬次
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}

可以自己試一下,每次運行的結(jié)果可能是不同的,其原因是 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

到此這篇關(guān)于JavaScript實現(xiàn)隨機產(chǎn)生字符串的方法分享的文章就介紹到這了,更多相關(guān)JavaScript隨機產(chǎn)生字符串內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論