js实现生成一个随机的指定长度的key

js实现生成一个随机的指定长度的key

function generateKey(keyLength = 18) {
    
    
  let rlt = ''
  for (let i = 0; i < keyLength; i++) {
    
    
    if (Math.round(Math.random())) {
    
    
      rlt += Math.ceil(Math.random() * 9)
    } else {
    
    
      const ranNum = Math.ceil(Math.random() * 23)
      if (Math.round(Math.random())) {
    
    
        rlt += String.fromCharCode(65 + ranNum)
      } else {
    
    
        rlt += String.fromCharCode(97 + ranNum)
      }
    }
    //加上-,不要的可以去掉
    if ((i + 1) % 6 === 0 && i > 2 && i < 17) {
    
    
      rlt += '-'
    }
  }
  return rlt
}

key由数组和大小写字母组成,中间用-分割

const a = generateKey(16) // 91Sw86-t1P3UI-B6Sx
const b = generateKey() // b4TGq1-42Se7m-49d233
const c = generateKey(20) // n44Ix5-VIU8r5-J7b8I5E2

猜你喜欢

转载自blog.csdn.net/jojo1001/article/details/121357194