一起学习前端

js如何生成唯一标识符(类似uuid)

2019-11-16  本文已影响0人  费莱姆

1. JavaScript唯一ID生成器Nano ID

NanoID: 一个极小的,安全的ID生成器
Source:https://github.com/ai/nanoid

npm i nanoid
    const nanoid = require('nanoid')

    console.log(nanoid());  // Hz8ODbd-zGlWCURoLbREe
    
    console.log(nanoid(8)) // r1Qxk61m

    const generate = require('nanoid/generate');
    
    model.id = generate('1234567890abcdef', 10); //=> a082c43d4e
    
    // 如果要使用相同的URL友好符号,只需更改长度,
    const url = require('nanoid/url');
    
    model.id = generate(url, 10); //=> WK5Rp2Nqkd
    const format = require('nanoid/format')
     
    function random (size) {
      const result = []
      for (let i = 0; i < size; i++) {
        result.push(randomByte())
      }
      return result
    }
     
    format(random, "abcdef", 10) //=> "fbaefaadeb"
    const nonSecure = require('nanoid/non-secure')
    
    const id = nonSecure() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
    const nanoid = require('nanoid/async')
     
    async function createUser () {
      user.id = await nanoid()
    }
    const format = require('nanoid/async/format')
    const url = require('nanoid/url')
     
    function random (size) {
      return new Promise(…)
    }
     
    async function createUser () {
      user.id = await format(random, url, 10)
    }
上一篇下一篇

猜你喜欢

热点阅读