JavaScript does not generate a duplicate ID

/**
 * 生成一个用不重复的ID
 */
function GenNonDuplicateID():String{
  
}

Take a look at a few of the following methods

1. Generate [0,1) Math.random random number, e.g.

//我这次运行生成的是:0.5834165740043102
Math.random()

2. Obtain current timestamp Date.now

//现在时间戳是1482645606622
Date.now() = 1521009303858

3. The decimal hexadecimal string into other Number.toString

//将1482645606622转换成二进制:10101100100110100100100001001000011011110
(1482645606622).toString(2)
//转换成16进制:159349090de MongDB中的ObjectID就是24位16进制数
(1482645606622).toString(16);
//最大进制支持转为36进制,使用字符是0-9a-z :ix48wvry
(1482645606622).toString(36)

GenNonDuplicateID of self-evolution

1. random number version v0.0.1

/**
 * 生成一个用不重复的ID
 */
function GenNonDuplicateID(){
  return Math.random().toString()
}

//生成一个类似 0.1283460319177394的ID
GenNonDuplicateID()

2. random number version hexadecimal version v0.0.2

/**
 * 生成一个用不重复的ID
 */
function GenNonDuplicateID(){
  return Math.random().toString(16)
}

//函数将生成类似 0.c1615913fa915 的ID
GenNonDuplicateID()

3. random binary version v0.0.3 version 36

/**
 * 生成一个用不重复的ID
 */
function GenNonDuplicateID(){
  return Math.random().toString(36)
}

//函数将生成类似 0.hefy7uw6ddzwidkwcmxkzkt9 的ID
GenNonDuplicateID()

4. The random number hexadecimal 36 version version removed "0." v0.0.4

/**
 * 生成一个用不重复的ID
 */
function GenNonDuplicateID(){
  return Math.random().toString(36).substr(3)
}

//函数将生成类似 8dlv9vabygks2cbg1spds4i 的ID
GenNonDuplicateID()

However, with a random number as ID, as the cumulative frequency of use, both bound to the same ID

The introduction of the 36 micro-stamp band version v0.1.1

/**
 * 生成一个用不重复的ID
 */
function GenNonDuplicateID(){
  let idStr = Date.now().toString(36)
  idStr += Math.random().toString(36).substr(3)
  return idStr
}

//函数将生成类似 ix49sfsnt7514k5wpflyb5l2vtok9y66r 的ID
GenNonDuplicateID()

6. The introduction of time stamps added to 36 micro-ary versions random length control v0.1.2

/**
 * 生成一个用不重复的ID
 */
function GenNonDuplicateID(randomLength){
  let idStr = Date.now().toString(36)
  idStr += Math.random().toString(36).substr(3,randomLength)
  return idStr
}

// GenNonDuplicateID(3) 将生成类似 ix49wl2978w 的ID
GenNonDuplicateID(3)

Thus several front ID generation is always the same, looking unhappy, then again changed to change

7. The introduction of random preamble stamp added random number hexadecimal 36 length control v0.1.3

/**
 * 生成一个用不重复的ID
 */
function GenNonDuplicateID(randomLength){
  return Number(Math.random().toString().substr(3,randomLength) + Date.now()).toString(36)
}
//GenNonDuplicateID()将生成 rfmipbs8ag0kgkcogc 类似的ID
GenNonDuplicateID()

Guess you like

Origin www.cnblogs.com/alterem/p/11526463.html