JavaScript を使用して動的 ID を生成する


数学乱数を使用して単純な ID ジェネレーターを作成する





const generateID = ()=> {
   return Math.random().toString(36).slice(2)
}


// How to use

const UID = generateID() 




長さを制御して動的 ID を生成する





const generateID = (length)=> {
   const id = Math.random().toString(36).slice(2);
   const uid = [...Array(length)].reduce((r)=> {
           return r+id[~~(Math.random()*id.length)]
   }, '')
}


// How to use

const UID = generateID(8) 




RFc 標準で UUID を生成する



RFc 標準 UUID は xxxxxxxx-Mxxx-Nxxx-xxxxxxxxxxxx の形式である必要があります.ここで、x は [0-9, a-f] のいずれかです M は [1-5] のいずれかであり、N は [8,9,a または b ] です


const generateUUID= ()=> {
   const placeholder = [1e7]+-1e3+-4e3+-8e3+-1e11;
   const uid = () => {
     const id = crypto.getRandomValues(new Uint8Array(1));
     return (uid ^ id[0] & 15 >> uid / 4).toString(16)
   }
   return placeholder.replace(/[018]/g, uid)
}


// How to use

const UUID = generateUUID()