如何使用 JavaScript 创建唯一 ID?

发布于 2024-09-09 07:07:33 字数 1094 浏览 2 评论 0原文

我有一个表单,用户可以在其中为多个城市添加多个选择框。问题是每个新生成的选择框都需要有一个唯一的 id。这可以用 JavaScript 完成吗?

这是选择城市的表格部分。另请注意,当选择特定州时,我使用一些 PHP 来填充城市。

<form id="form" name="form" method="post" action="citySelect.php">
<select id="state" name="state" onchange="getCity()">
    <option></option>
    <option value="1">cali</option>
    <option value="2">arizona</option>
    <option value="3">texas</option>
</select>
<select id="city" name="city" style="width:100px">
    
</select>

    <br/>
</form>

这是 JavaScript:

$("#bt").click(function() {

$("#form").append(
       "<select id='state' name='state' onchange='getCity()'>
           <option></option>
           <option value='1'>cali</option>
           <option value='2'>arizona</option>
           <option value='3'>texas</option>
        </select>
        <select id='city' name='city' style='width:100px'></select><br/>"
     );
});

I have a form where a user can add multiple select boxes for multiple cities. The problem is that each newly generated select box needs to have a unique id. Can this be done in JavaScript?

Here is the part of the form for selecting cities. Also note that I'm using some PHP to fill in the cities when a specific state is selected.

<form id="form" name="form" method="post" action="citySelect.php">
<select id="state" name="state" onchange="getCity()">
    <option></option>
    <option value="1">cali</option>
    <option value="2">arizona</option>
    <option value="3">texas</option>
</select>
<select id="city" name="city" style="width:100px">
    
</select>

    <br/>
</form>

Here is the JavaScript:

$("#bt").click(function() {

$("#form").append(
       "<select id='state' name='state' onchange='getCity()'>
           <option></option>
           <option value='1'>cali</option>
           <option value='2'>arizona</option>
           <option value='3'>texas</option>
        </select>
        <select id='city' name='city' style='width:100px'></select><br/>"
     );
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

A君 2024-09-16 07:07:33
    var id = "id" + Math.random().toString(16).slice(2)
    
    console.log(id)

    var id = "id" + Math.random().toString(16).slice(2)
    
    console.log(id)

情泪▽动烟 2024-09-16 07:07:33
   const uid = function(){
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    }
    
    console.log(uid())

该函数生成非常唯一的 ID,并按其生成日期排序。
也可用于数据库中的 ID。

   const uid = function(){
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    }
    
    console.log(uid())

This Function generates very unique IDs that are sorted by its generated Date.
Also useable for IDs in Databases.

北笙凉宸 2024-09-16 07:07:33

使用毫秒计时器的另一种方式:

var uniq = 'id' + (new Date()).getTime();

console.log(uniq)

another way it to use the millisecond timer:

var uniq = 'id' + (new Date()).getTime();

console.log(uniq)

雨的味道风的声音 2024-09-16 07:07:33

你不能只保留一个运行索引吗?

var _selectIndex = 0;

...code...
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);

编辑

经过进一步考虑,您实际上可能更喜欢为您的选择使用数组样式名称...

例如

<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>

,在 php 的服务器端,例如:

$cities = $_POST['city']; //array of option values from selects

编辑 2 在对OP评论的响应

使用DOM方法动态创建选项可以如下完成:

var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);

var city = null,city_opt=null;
for (var i=0, len=cities.length; i< len; i++) {
    city = cities[i];
    var city_opt = document.createElement("option");
    city_opt.setAttribute("value",city);
    city_opt.appendChild(document.createTextNode(city));
    newSelectBox.appendChild(city_opt);
}
document.getElementById("example_element").appendChild(newSelectBox);

假设cities数组已经存在

或者您可以使用innerHTML方法......

var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
document.getElementById("example_element").appendChild(newSelectBox);

var city = null,htmlStr="";
for (var i=0, len=cities.length; i< len; i++) {
    city = cities[i];
    htmlStr += "<option value='" + city + "'>" + city + "</option>";
}
newSelectBox.innerHTML = htmlStr;

could you not just keep a running index?

var _selectIndex = 0;

...code...
var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);

EDIT

Upon further consideration, you may actually prefer to use array-style names for your selects...

e.g.

<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>
<select name="city[]"><option ..../></select>

then, on the server side in php for example:

$cities = $_POST['city']; //array of option values from selects

EDIT 2 In response to OP comment

Dynamically creating options using DOM methods can be done as follows:

var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);

var city = null,city_opt=null;
for (var i=0, len=cities.length; i< len; i++) {
    city = cities[i];
    var city_opt = document.createElement("option");
    city_opt.setAttribute("value",city);
    city_opt.appendChild(document.createTextNode(city));
    newSelectBox.appendChild(city_opt);
}
document.getElementById("example_element").appendChild(newSelectBox);

assuming that the cities array already exists

Alternatively you could use the innerHTML method.....

var newSelectBox = document.createElement("select");
newSelectBox.setAttribute("id","select-"+_selectIndex++);
document.getElementById("example_element").appendChild(newSelectBox);

var city = null,htmlStr="";
for (var i=0, len=cities.length; i< len; i++) {
    city = cities[i];
    htmlStr += "<option value='" + city + "'>" + city + "</option>";
}
newSelectBox.innerHTML = htmlStr;
木落 2024-09-16 07:07:33

最短且没有库,也适用于nodejs

crypto.randomUUID();
// 'a63ae209-ec69-4867-af8a-6f4d1efe15c6'

https://developer .mozilla.org/en-US/docs/Web/API/Crypto/randomUUID

btn.onclick = () => myID.textContent = crypto.randomUUID()
<button id="btn">Generate ID</button>
<myID id="myID"></myID>

The shortest and without libraries, also works in nodejs

crypto.randomUUID();
// 'a63ae209-ec69-4867-af8a-6f4d1efe15c6'

https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID

btn.onclick = () => myID.textContent = crypto.randomUUID()
<button id="btn">Generate ID</button>
<myID id="myID"></myID>

也只是曾经 2024-09-16 07:07:33
function uniqueid() {
  // always start with a letter (for DOM friendlyness)
  var idstr = String.fromCharCode(Math.floor((Math.random() * 25) + 65));
  do {
    // between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
    var ascicode = Math.floor((Math.random() * 42) + 48);
    if (ascicode < 58 || ascicode > 64) {
      // exclude all chars between : (58) and @ (64)
      idstr += String.fromCharCode(ascicode);
    }
  } while (idstr.length < 32);

  return (idstr);
}

console.log(uniqueid());

function uniqueid() {
  // always start with a letter (for DOM friendlyness)
  var idstr = String.fromCharCode(Math.floor((Math.random() * 25) + 65));
  do {
    // between numbers and characters (48 is 0 and 90 is Z (42-48 = 90)
    var ascicode = Math.floor((Math.random() * 42) + 48);
    if (ascicode < 58 || ascicode > 64) {
      // exclude all chars between : (58) and @ (64)
      idstr += String.fromCharCode(ascicode);
    }
  } while (idstr.length < 32);

  return (idstr);
}

console.log(uniqueid());

生生漫 2024-09-16 07:07:33

不需要外部库。证明了唯一性。

你可以做这样的事情。

// Function to generate unique id

const uniqueId = (length=16) => {
  return parseInt(Math.ceil(Math.random() * Date.now()).toPrecision(length).toString().replace(".", ""))
}

// ----------------------------

document.querySelector("#butt01").onclick = () => {
  document.querySelector("#span01").innerHTML = uniqueId()
}

ids = new Set()
count = 0

document.querySelector("#butt02").onclick = () => {
  for (let i = 0; i< 1000; i++){
    ids.add(uniqueId())
  }

  document.querySelector("#span02").innerHTML = `Found ${1000 - ids.size} duplicated random values.`
}
<div>
    <button id="butt01">Generate</button>
    <span id="span01"></span>
    <hr>
    <button id="butt02">Check collision potentiality in 1000 cases</button>
    <span id="span02"></span>
</div>

将自纪元以来的时间(以毫秒为单位)与随机值乘以固定大小。

运行此命令以查看可能的冲突。

你会发现无论是 1000、10000 还是 1000000000,都不会发生冲突。

如果两个用户同时生成 id 并获得相同的随机数,那么这种可能性很小。

为了增加唯一性,您可以将日期乘以更多 Math.random()

No external libraries needed. Uniqueness proved.

You could do something like this.

// Function to generate unique id

const uniqueId = (length=16) => {
  return parseInt(Math.ceil(Math.random() * Date.now()).toPrecision(length).toString().replace(".", ""))
}

// ----------------------------

document.querySelector("#butt01").onclick = () => {
  document.querySelector("#span01").innerHTML = uniqueId()
}

ids = new Set()
count = 0

document.querySelector("#butt02").onclick = () => {
  for (let i = 0; i< 1000; i++){
    ids.add(uniqueId())
  }

  document.querySelector("#span02").innerHTML = `Found ${1000 - ids.size} duplicated random values.`
}
<div>
    <button id="butt01">Generate</button>
    <span id="span01"></span>
    <hr>
    <button id="butt02">Check collision potentiality in 1000 cases</button>
    <span id="span02"></span>
</div>

Multiply time in milliseconds since epoch with a random value to fixed size.

Run this to see possible collisions.

You would see there are no collisions whether it is 1000, 10000 or 1000000000.

It would have a very small chance if two users generate ids at the same time and gets the rame random number.

To increase the uniqueness you could multiply date more Math.random()s.

困倦 2024-09-16 07:07:33

非常短的函数将为您提供唯一的 ID:

var uid = (function() {
  var id = 0;
  return function() {
    if (arguments[0] === 0) id = 0;
    return id++;
  }
})();

console.log(uid());
console.log(uid());
console.log(uid());

Very short function will give you unique ID:

var uid = (function() {
  var id = 0;
  return function() {
    if (arguments[0] === 0) id = 0;
    return id++;
  }
})();

console.log(uid());
console.log(uid());
console.log(uid());

机场等船 2024-09-16 07:07:33

我正在研究与OP类似的问题,并发现@Guy和@Scott的解决方案的元素可以组合起来创建一个在我看来更可靠的解决方案。此处生成的唯一 id 具有以下划线分隔的三个部分:

  1. 前导字母;
  2. 以 36 进制显示的时间戳;
  3. 最后是随机部分。

这个解决方案应该工作得很好,即使对于非常大的集合:

function uniqueId() {
  // desired length of Id
  var idStrLen = 32;
  // always start with a letter -- base 36 makes for a nice shortcut
  var idStr = (Math.floor((Math.random() * 25)) + 10).toString(36) + "_";
  // add a timestamp in milliseconds (base 36 again) as the base
  idStr += (new Date()).getTime().toString(36) + "_";
  // similar to above, complete the Id using random, alphanumeric characters
  do {
    idStr += (Math.floor((Math.random() * 35))).toString(36);
  } while (idStr.length < idStrLen);

  return (idStr);
}

console.log(uniqueId())

I'm working on a similar problem to the OP, and found that elements of the solutions from @Guy and @Scott can be combined to create a solution that's more solid IMO. The resulting unique id here has three sections separated by underscores:

  1. A leading letter;
  2. A timestamp displayed in base 36;
  3. And a final, random section.

This solution should work really well, even for very large sets:

function uniqueId() {
  // desired length of Id
  var idStrLen = 32;
  // always start with a letter -- base 36 makes for a nice shortcut
  var idStr = (Math.floor((Math.random() * 25)) + 10).toString(36) + "_";
  // add a timestamp in milliseconds (base 36 again) as the base
  idStr += (new Date()).getTime().toString(36) + "_";
  // similar to above, complete the Id using random, alphanumeric characters
  do {
    idStr += (Math.floor((Math.random() * 35))).toString(36);
  } while (idStr.length < idStrLen);

  return (idStr);
}

console.log(uniqueId())

阳光下的泡沫是彩色的 2024-09-16 07:07:33

您可以使用计时器生成 ID,并使用 performance.now() 避免重复

id = 'id' + performance.now()
dup = 'id' + performance.now()

console.log(id)
console.log(id.replace('.','')) // sexy id
console.log(id === dup) // false!
.as-console-wrapper{border-top: none !important;overflow-y: auto !important;top: 0;}

请注意,高分辨率时间 API 在所有最新浏览器中均可用


编辑(根据 Ciprian 的评论):不幸的是,这还不够,performance.now() 仅精确到毫秒。考虑将其与 Math.random() 结合使用:

const generateId = () => `${performance.now()}${Math.random().toString().slice(5)}`.replace('.','')

let id = generateId()
let dup = generateId()

console.log(id)
console.log(id === dup) // false!

let ary = [...Array(1000)].map(_ => generateId())
console.log((new Set(ary)).size === 1000) // no dups!
.as-console-wrapper{border-top: none !important;overflow-y: auto !important;top: 0;}

You could generate an ID using a timer and avoiding duplicates using performance.now():

id = 'id' + performance.now()
dup = 'id' + performance.now()

console.log(id)
console.log(id.replace('.','')) // sexy id
console.log(id === dup) // false!
.as-console-wrapper{border-top: none !important;overflow-y: auto !important;top: 0;}

Note that the High resolution time API is available in all recent browsers.


EDIT(per Ciprian's comment): That is unfortunately not enough, performance.now() is only precise to the millisecond. Consider using it in conjuction with Math.random():

const generateId = () => `${performance.now()}${Math.random().toString().slice(5)}`.replace('.','')

let id = generateId()
let dup = generateId()

console.log(id)
console.log(id === dup) // false!

let ary = [...Array(1000)].map(_ => generateId())
console.log((new Set(ary)).size === 1000) // no dups!
.as-console-wrapper{border-top: none !important;overflow-y: auto !important;top: 0;}

情绪少女 2024-09-16 07:07:33

回复@scott:
有时 JS 运行得很快...所以...

var uniqueId = null;
var getUniqueName = function(prefix) {
    if (!uniqueId) uniqueId = (new Date()).getTime();
    return (prefix || 'id') + (uniqueId++);
  };

console.log(getUniqueName())
console.log(getUniqueName())
console.log(getUniqueName())

In reply to @scott :
Sometime JS go very fast... so...

var uniqueId = null;
var getUniqueName = function(prefix) {
    if (!uniqueId) uniqueId = (new Date()).getTime();
    return (prefix || 'id') + (uniqueId++);
  };

console.log(getUniqueName())
console.log(getUniqueName())
console.log(getUniqueName())

疾风者 2024-09-16 07:07:33

在您的命名空间中放入一个类似于以下实例的实例

var myns = {/*.....*/};
myns.uid = new function () {
    var u = 0;
    this.toString = function () {
        return 'myID_' + u++;
    };
};
console.dir([myns.uid, myns.uid, myns.uid]);

put in your namespace an instance similar to the following one

var myns = {/*.....*/};
myns.uid = new function () {
    var u = 0;
    this.toString = function () {
        return 'myID_' + u++;
    };
};
console.dir([myns.uid, myns.uid, myns.uid]);
最舍不得你 2024-09-16 07:07:33

您可以使用 ES6 中引入的 Generator 函数(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

const idCreator = function*() {
  let i = 0;
  while (true) yield i++;
};

const idsGenerator = idCreator();
const generateId = () => idsGenerator.next().value;

console.log(generateId()) // 0
console.log(generateId()) // 1
console.log(generateId()) // 2

You can use the Generator function, was introduced in ES6 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*)

const idCreator = function*() {
  let i = 0;
  while (true) yield i++;
};

const idsGenerator = idCreator();
const generateId = () => idsGenerator.next().value;

console.log(generateId()) // 0
console.log(generateId()) // 1
console.log(generateId()) // 2

记忆之渊 2024-09-16 07:07:33

随机不是唯一的。时间值唯一。这些概念非常不同,当您的应用程序扩展和分布式时,这种差异就会显现出来。上面的许多答案都有潜在的危险。

解决发帖者问题的更安全方法是 UUID:Create GUID / UUID in JavaScript?

Random is not unique. Times values are not unique. The concepts are quite different and the difference rears its ugly head when your application scales and is distributed. Many of the answers above are potentially dangerous.

A safer approach to the poster's question is UUIDs: Create GUID / UUID in JavaScript?

月隐月明月朦胧 2024-09-16 07:07:33

有两个软件包可用于此目的。

  • 对于简短的唯一 ID 生成 nanoid link
import { nanoid } from 'nanoid'
const id = nanoid()    // "Uakgb_J5m9g-0JDMbcJqLJ"
const id = nanoid(10)  // "jcNqc0UAWK"
  • 对于通用唯一 id生成 uuid 链接
import { v4 as uuidv4 } from 'uuid';
const id= uuidv4();    // quite big id

There are two packages available for this.

  • For short unique id generation nanoid link
import { nanoid } from 'nanoid'
const id = nanoid()    // "Uakgb_J5m9g-0JDMbcJqLJ"
const id = nanoid(10)  // "jcNqc0UAWK"
  • For universally unique id generation uuid link
import { v4 as uuidv4 } from 'uuid';
const id= uuidv4();    // quite big id
找个人就嫁了吧 2024-09-16 07:07:33

为了避免创建任何计数器并确保 id 是唯一的,即使有一些其他组件在页面上创建带有 id 的元素,您可以使用随机数,如果它不够好则更正它(但您也必须立即设置 id 以避免冲突):

var id = "item"+(new Date()).getMilliseconds()+Math.floor(Math.random()*1000);
 // or use any random number generator
 // whatever prefix can be used instead of "item"
while(document.getElementById(id))
    id += 1;
//# set id right here so that no element can get that id between the check and setting it

To avoid creating any counters and be sure that the id is unique even if there are some other components that create elements with ids on the page, you can use a random number and than correct it if it's not good enough (but you also have to set the id immediately to avoid conflicts):

var id = "item"+(new Date()).getMilliseconds()+Math.floor(Math.random()*1000);
 // or use any random number generator
 // whatever prefix can be used instead of "item"
while(document.getElementById(id))
    id += 1;
//# set id right here so that no element can get that id between the check and setting it
開玄 2024-09-16 07:07:33

我认为如果你真的想拥有一个唯一ID,那么最好的方法是使用如下库:
uuiduniqueid

注意< /em>: 唯一 ID随机 ID 不同

仅使用日期时间毫秒的方法是错误的。
如今,计算机速度足够快,能够在一毫秒内运行多次循环迭代。

npm install uuid

导入库:

如果您使用 ES 模块

import { v4 as uuidv4 } from 'uuid';

对于 CommonJS:

const { v4: uuidv4 } = require('uuid');

用法

uuidv4();

// This will output something like: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d

I think if you really want to have a unique ID then the best approach is to use a library like:
uuid or uniqueid

Note: Unique ID is not the same as Random ID

To use only date time milliseconds approach is wrong.
Nowadays computers are fast enough and able to run more than one iteration of a loop in a single millisecond.

npm install uuid

Importing the library:

If you are using ES modules

import { v4 as uuidv4 } from 'uuid';

And for CommonJS:

const { v4: uuidv4 } = require('uuid');

Usage:

uuidv4();

// This will output something like: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d
预谋 2024-09-16 07:07:33

就像其他人所说的那样,您可以使用运行索引,或者如果您不喜欢使用变量的想法,只需提取列表中最后一个城市的 id 并将 1 添加到其 id 中。

Like others said you can use a running index, or if you don't like the idea of using a variable just pull the id of the last city in the list and add 1 to its id.

玉环 2024-09-16 07:07:33

警告:这个答案可能不利于这个问题的总体意图,但我还是把它发布在这里,因为它解决了这个问题的部分版本。

您可以使用 lodash 的 uniqueId(文档此处)。对于数据库记录或在浏览器中保存会话或类似内容的东西来说,这不是一个好的 uniqueId 生成器。但我来这里寻找这个的原因是通过使用它来解决的。如果你需要一个唯一的 id 来处理足够短暂的事情,这就可以了。

我需要它是因为我正在创建一个可重用的反应组件,该组件具有标签和表单控件。标签需要有一个 for="controlId" 属性,与实际表单控件(input 或 select 元素)具有的 id="controlId" 相对应。在这种情况下,这个 id 不是必需的,但我需要为两个属性生成一个 id 来共享,并确保该 id 在正在呈现的页面上下文中是唯一的。所以lodash的功能运行得很好。以防万一对其他人有用。

Warning: This answer may not be good for the general intent of this question, but I post it here nevertheless, because it solves a partial version of this issue.

You can use lodash's uniqueId (documentation here). This is not a good uniqueId generator for say, db records, or things that will persist a session in a browser or something like that. But the reason I came here looking for this was solved by using it. If you need a unique id for something transient enough, this will do.

I needed it because I was creating a reusable react component that features a label and a form control. The label needs to have a for="controlId" attribute, corresponding to the id="controlId" that the actual form control has (the input or select element). This id is not necessary out of this context, but I need to generate one id for both attributes to share, and make sure this id is unique in the context of the page being rendered. So lodash's function worked just fine. Just in case is useful for someone else.

别想她 2024-09-16 07:07:33

如果您只是想创建一个唯一的 ID:

  • 不需要字符串化/序列化
  • 不需要在 IE 等旧版浏览器中工作

那么您可以简单地使用 const someId = Symbol();< /code> 确保唯一性。

这对于提交到 PHP 脚本的表单不起作用。但是,我想确保在这里捕获这一点,以防其他人正在寻找更通用的唯一 ID 方法。

If you're just looking to create a unique ID that:

  • Doesn't ever need to be stringified/serialized
  • Doesn't need to work in legacy browsers like IE

Then you can simply use const someId = Symbol(); for guaranteed uniqueness.

This would not work for your form which submits to a PHP script. But, I want to make sure to capture this here in case others are looking for a more generic approach to unique IDs.

楠木可依 2024-09-16 07:07:33

只需两分钱

function makeId(tokenLen) {
  if (tokenLen == null) {
    tokenLen = 16;
  }
  var text = "";
  const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for (var i = 0; i < tokenLen; ++i)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

console.log(makeId(10))

Just two cents

function makeId(tokenLen) {
  if (tokenLen == null) {
    tokenLen = 16;
  }
  var text = "";
  const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  for (var i = 0; i < tokenLen; ++i)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

console.log(makeId(10))

我三岁 2024-09-16 07:07:33

看看这个函数,它会完成你的工作。

如果您想要字符串中包含大写和小写字符:

function generateId(length) {
  var id = '';
  while (id.length < length) {
    var ch = Math.random()
      .toString(36)
      .substr(2, 1);
    if (Math.random() < 0.5) {
      ch = ch.toUpperCase();
    }
    id += ch;
  }
  return id;
}

console.log(generateId(10))

仅小写字符:

function generateId(length) {
  var id = '';
  while (id.length < length) {
    id += Math.random()
      .toString(36)
      .substr(2, 1);
  }
  return id;
}

console.log(generateId(10))

Look at this functions, it will get ur job done.

If u want uppercase and lowercase chars in ur string:

function generateId(length) {
  var id = '';
  while (id.length < length) {
    var ch = Math.random()
      .toString(36)
      .substr(2, 1);
    if (Math.random() < 0.5) {
      ch = ch.toUpperCase();
    }
    id += ch;
  }
  return id;
}

console.log(generateId(10))

Only lowercase chars:

function generateId(length) {
  var id = '';
  while (id.length < length) {
    id += Math.random()
      .toString(36)
      .substr(2, 1);
  }
  return id;
}

console.log(generateId(10))

三生池水覆流年 2024-09-16 07:07:33
function generateId() {

  return Math.random().toString(36).substring(2) +
    (new Date()).getTime().toString(36);
}

console.log(generateId())

function generateId() {

  return Math.random().toString(36).substring(2) +
    (new Date()).getTime().toString(36);
}

console.log(generateId())

棒棒糖 2024-09-16 07:07:33

简单的解决方案:)

const ID = (_length = 13) => {
  // Math.random to base 36 (numbers, letters),
  // grab the first 9 characters
  // after the decimal.
  return '_' + Math.random().toString(36).substr(2, _length); // max _length should be less then 13
};
console.log("Example ID()::", ID())

Simple Solution :)

const ID = (_length = 13) => {
  // Math.random to base 36 (numbers, letters),
  // grab the first 9 characters
  // after the decimal.
  return '_' + Math.random().toString(36).substr(2, _length); // max _length should be less then 13
};
console.log("Example ID()::", ID())

我们只是彼此的过ke 2024-09-16 07:07:33

您可以利用闭包

var i = 0;
function generateId() {
    return i++;
}

如果你想附上它:

function generator() {
  var i = 0;
  return function() {
    return i++;
  };
}

var generateId = generator();
console.log(generateId()); //1
console.log(generateId()); //2

generator 可以接受默认前缀; generateId 可以接受可选后缀:

function generator(prefix) {
  var i = 0;
  return function(suffix) {
    return prefix + (i++) + (suffix || '');
  };
}

var generateId = generator('_');
console.log(generateId('_')); //_1_
console.log(generateId('@')); //_2@

如果您希望 id 指示一个序列,这会很方便,非常类似于 new Date().getTime(),但更易于阅读。

You could take advantage of closure.

var i = 0;
function generateId() {
    return i++;
}

If you want to enclose it:

function generator() {
  var i = 0;
  return function() {
    return i++;
  };
}

var generateId = generator();
console.log(generateId()); //1
console.log(generateId()); //2

generator could accept a default prefix; generateId coud accept an optional suffix:

function generator(prefix) {
  var i = 0;
  return function(suffix) {
    return prefix + (i++) + (suffix || '');
  };
}

var generateId = generator('_');
console.log(generateId('_')); //_1_
console.log(generateId('@')); //_2@

This comes in handy if you want your id to indicate a sequence, very much like new Date().getTime(), but easier to read.

橘寄 2024-09-16 07:07:33

这是一个函数(下面的函数 genID()),它根据您想要的任何 id 前缀/ID 递归检查 DOM 的唯一性。

在你的情况下,你可能会这样使用它

var seedNum = 1;
newSelectBox.setAttribute("id",genID('state-',seedNum));

function genID(myKey, seedNum) {
  var key = myKey + seedNum;
  if (document.getElementById(key) != null) {
    return genID(myKey, ++seedNum);
  } else {
    return key;
  }
}

console.log(genID('key', 1))

Here is a function (function genID() below) that recursively checks the DOM for uniqueness based on whatever id prefex/ID you want.

In your case you'd might use it as such

var seedNum = 1;
newSelectBox.setAttribute("id",genID('state-',seedNum));

function genID(myKey, seedNum) {
  var key = myKey + seedNum;
  if (document.getElementById(key) != null) {
    return genID(myKey, ++seedNum);
  } else {
    return key;
  }
}

console.log(genID('key', 1))

你的呼吸 2024-09-16 07:07:33

这是我自己根据创建的元素的 xpath 的看法:

/** Returns the XPATH of an element **/
var getPathTo = function(element) {
  if (element===document.body)
      return element.tagName;

  var ix= 0;
  var siblings= element.parentNode.childNodes;
  for (var i= 0; i<siblings.length; i++) {
      var sibling= siblings[i];
      if (sibling===element)
          // stripped xpath (parent xpath + tagname + index)
          return getPathTo(element.parentNode)+ element.tagName + ix+1;
      if (sibling.nodeType===1 && sibling.tagName===element.tagName)
          ix++;
   }
}

/** hashcode function (credit http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery **/
var hashCode = function(str) {
  var hash = 0, i, chr, len;
  if (str.length === 0) return hash;
  for (i = 0, len = str.length; i < len; i++) {
    chr   = str.charCodeAt(i);
    hash  = ((hash << 5) - hash) + chr;
    hash |= 0; // Convert to 32bit integer
 }
return hash;
};

/** Genaretes according to xpath + timestamp **/
var generateUID = function(ele)
{
  return hashCode(getPathTo(ele)) + new Date().getTime();
}

首先获取元素的 xpath。

然后计算 xpath 的哈希码。因此,每个 xpath 都有一个唯一的 id。

这里的问题是,如果动态生成唯一元素,则 xpath 不一定是唯一的。因此我们在末尾添加时间戳。

也许我们还可以通过添加最后的 Math.Random() 来保证更多独特的元素。

Here's my own take at it based on the xpath of the element created :

/** Returns the XPATH of an element **/
var getPathTo = function(element) {
  if (element===document.body)
      return element.tagName;

  var ix= 0;
  var siblings= element.parentNode.childNodes;
  for (var i= 0; i<siblings.length; i++) {
      var sibling= siblings[i];
      if (sibling===element)
          // stripped xpath (parent xpath + tagname + index)
          return getPathTo(element.parentNode)+ element.tagName + ix+1;
      if (sibling.nodeType===1 && sibling.tagName===element.tagName)
          ix++;
   }
}

/** hashcode function (credit http://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery **/
var hashCode = function(str) {
  var hash = 0, i, chr, len;
  if (str.length === 0) return hash;
  for (i = 0, len = str.length; i < len; i++) {
    chr   = str.charCodeAt(i);
    hash  = ((hash << 5) - hash) + chr;
    hash |= 0; // Convert to 32bit integer
 }
return hash;
};

/** Genaretes according to xpath + timestamp **/
var generateUID = function(ele)
{
  return hashCode(getPathTo(ele)) + new Date().getTime();
}

First the xpath of the element is fetched.

The hashcode of the xpath is then computed. We therefore have a unique id per xpath.

The problem here is that xpath are not necesseraly unique if unique elements are generated on the fly. Thus we add the timestamp at the end.

Maybe we could also garantee more unique elements by adding a final Math.Random().

骄兵必败 2024-09-16 07:07:33

如果需要在 TypeScript 中生成 GUID,可以使用 guid-typescript 包,为此目的提供了一个 Guid 类。

要使用它,您可以通过 npm 安装该包:
npm i guid-typescript --save

然后,在您的 TypeScript 代码中,您可以导入 Guid 类并创建新的 GUID,如下所示:

import { Guid } from "guid-typescript";

const myGuid: Guid = Guid.create(); // e.g., "b77d409a-10cd-4a47-8e94-b0cd0ab50aa1"

我希望这会有所帮助

If you need to generate GUIDs in TypeScript, you can use the guid-typescript package, which provides a Guid class for this purpose.

To use it, you can install the package via npm:
npm i guid-typescript --save

Then, in your TypeScript code, you can import the Guid class and create new GUIDs as follows:

import { Guid } from "guid-typescript";

const myGuid: Guid = Guid.create(); // e.g., "b77d409a-10cd-4a47-8e94-b0cd0ab50aa1"

I hope this help ????

寄意 2024-09-16 07:07:33

为了生成唯一的 id:

const uid = () =>
  String(
    Date.now().toString(32) +
    Math.random().toString(32) +
    Math.random().toString(32)
  ).replace(/\./g, '')

console.log(uid())

// Test uniqueness
var size = 500000
var arr = new Array(size)
  .fill(0)
  .map(() => uid())

var b = new Set(arr)

console.log(
  size === b.size ? 'all ids are unique' : `not unique records ${size - b.size}`
)

For generate unique id's:

const uid = () =>
  String(
    Date.now().toString(32) +
    Math.random().toString(32) +
    Math.random().toString(32)
  ).replace(/\./g, '')

console.log(uid())

// Test uniqueness
var size = 500000
var arr = new Array(size)
  .fill(0)
  .map(() => uid())

var b = new Set(arr)

console.log(
  size === b.size ? 'all ids are unique' : `not unique records ${size - b.size}`
)

旧瑾黎汐 2024-09-16 07:07:33
const generateUniqueId = () => 'id_' + Date.now() + String(Math.random()).substr(2);

// if u want to check for collision
const arr = [];
const checkForCollision = () => {
  for (let i = 0; i < 10000; i++) {
    const el = generateUniqueId();
    if (arr.indexOf(el) > -1) {
      alert('COLLISION FOUND');
    }
    arr.push(el);
  }
};

console.log(generateUniqueId())

const generateUniqueId = () => 'id_' + Date.now() + String(Math.random()).substr(2);

// if u want to check for collision
const arr = [];
const checkForCollision = () => {
  for (let i = 0; i < 10000; i++) {
    const el = generateUniqueId();
    if (arr.indexOf(el) > -1) {
      alert('COLLISION FOUND');
    }
    arr.push(el);
  }
};

console.log(generateUniqueId())

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文