Javascript 特朗普。 也可用于数据库中的ID。
随机是不唯一的。时间值不是唯一的。这些概念是完全不同的,当您的应用程序进行扩展和分布时,这种差异会显现出来。上述许多答案都有潜在的危险 对于发帖人的问题,更安全的方法是UUIDs:Javascript 特朗普。 也可用于数据库中的ID。,javascript,html,select,dynamic,Javascript,Html,Select,Dynamic,随机是不唯一的。时间值不是唯一的。这些概念是完全不同的,当您的应用程序进行扩展和分布时,这种差异会显现出来。上述许多答案都有潜在的危险 对于发帖人的问题,更安全的方法是UUIDs:const generateUniqueId=()=>“id\uquen+Date.now()+String(Math.random()).substr(2); //如果你想检查碰撞 常数arr=[]; const checkForCollision=()=>{ for(设i=0;i-1){ 警报(“发现碰撞”); }
const generateUniqueId=()=>“id\uquen+Date.now()+String(Math.random()).substr(2);
//如果你想检查碰撞
常数arr=[];
const checkForCollision=()=>{
for(设i=0;i<10000;i++){
const el=generateUniqueId();
if(arr.indexOf(el)>-1){
警报(“发现碰撞”);
}
方位推力(el);
}
};
我认为,如果您真的想拥有一个唯一ID,那么最好的方法是使用一个库,如:或 注意:唯一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
不需要外部库。唯一性得到了证明。
你可以这样做
//生成唯一id的函数
const uniqueId=(长度=16)=>{
返回parseInt(Math.ceil(Math.random()*Date.now()).toPrecision(length.toString().replace(“.”,”))
}
// ----------------------------
document.querySelector(“#butt01”).onclick=()=>{
document.querySelector(“#span01”).innerHTML=uniqueId()
}
ids=[]
计数=0
document.querySelector(“#butt02”).onclick=()=>{
for(设i=0;i<1000;i++){
id.push(uniqueId())
}
用于(ID的el){
对于(ID的全部){
如果(el==ell&&ids.indexOf(el)!=ids.indexOf(ell)){
计数+=1
}
}
}
document.querySelector(“#span02”).innerHTML=`Found${count}重复的随机值`
}
生成
检查1000例碰撞可能性
看看这个小美人,这会让你的工作完成的
函数(长度){
变量id=“”;
do{id+=Math.random().toString(36).substr(2);}while(id.length
用于生成唯一id:
const uid = () =>
String(
Date.now().toString(32) +
Math.random().toString(32) +
Math.random().toString(32)
).replace(/\./g, '')
对于正在工作的检查:
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}`
)
有两个软件包可供选择
- 简而言之,生成唯一id
nanoid
- 用于通用唯一id生成
uuid
让transactionId=
${new Date().getDate()}${new Date().getHours()}${new Date().getSeconds()}${new Date().getmillizes()}
let transactionId=`${new Date().getDate()}${new Date().getHours()}${new Date().getSeconds()}${new Date().getmillizes()}`
console.log(transactionId)
您可以使用生成器函数,它是在ES6()中引入的
您是在使用Jquery之类的框架/工具包,还是仅仅使用vanilla js?另外,您是否可以发布一些代码,至少是生成的html输出?对于这种行为,您最好使用单选按钮。否则,在Javascript中,您可以使用类似“cities”的名称,然后使用类似“var i=0;”的迭代器对于每个选择框do.setAttribute('id','cities'+i)。getElementsByTagName(“?”)将在此处提供帮助。您需要提供一些示例HTML,以便有人能够真正提供帮助。您是否希望为每个新城市生成一个唯一的id属性?在javascript中,您可以维护对特定新DOM元素的引用,而不仅仅是它的id。因此,您不必生成唯一的id,这取决于您尝试执行的操作。我相信他是说他们可以列出一个或多个城市,每个都来自一个select。您可以看到相同的答案。如何使用此选项将标记插入select?请注意,使用运行的计数器可能会导致页面点击之间极有可能发生冲突。换句话说,如果每次加载页面时计数器都从1开始,那么下次编辑/更新对象时很可能会发生冲突。记住这一点很好。除非弄错了,否则这只会检查一次重复项?它不是检查重复项,而是增加最后一个数值。顺便问一下,您是否立即设置初始
uniqueId
,您不需要条件。您可能需要解释您的答案,以便于操作人员使用此示例生成相同ID的可能性有多大?似乎是可能的,但不太可能。考虑到javascript中的RNG是垃圾,它的可能性比你想象的要大;虽然(meh!==fun()){console.log('.');}在Chrome的命令行中…到目前为止,它有一百万个,没有重复项,对于大多数情况,这已经足够了。这个函数有可能生成相同的id,但是对于dom“friendlyness”来说+1似乎不是一个好主意(+new Date++new Date)/2===+new Date代码>如果用户在其他国家/地区创建ID会发生什么情况?\n如果您一个接一个地创建两个ID,则不会是唯一的<代码>var first=(新日期()).getTime();var second=(新日期()).getTime();log(第一个==第二个)如果是这样的话,你最好使用performance.now()
:performance.now()===performance.now()===false
@UlysseBN刚刚尝试了performance.now()
,但它在我的机器上并没有像你描述的那样工作,尽管具有超高分辨率,但如果您碰巧在页面上有一个元素的下一个id已在同一行中,则将失败。尽管是远程的,但冲突的概率不是空的。谢谢-下面是我为使用而修改的方法。我重用了代码,用var IdStr=''替换了字母行;然后我将idStrLen设置为
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;
var uniq = 'id' + (new Date()).getTime();
var uniqueId = null,
getUniqueName = function(prefix) {
if (!uniqueId) uniqueId = (new Date()).getTime();
return (prefix || 'id') + (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);
}
var uid = (function(){var id=0;return function(){if(arguments[0]===0)id=0;return id++;}})();
var myns = {/*.....*/};
myns.uid = new function () {
var u = 0;
this.toString = function () {
return 'myID_' + u++;
};
};
console.dir([myns.uid, myns.uid, myns.uid]);
var id = "id" + Math.random().toString(16).slice(2)
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);
}
/** 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();
}
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;
}
}
var i = 0;
function generateId() {
return i++;
}
function generator() {
var i = 0;
return function() {
return i++;
};
}
var generateId = generator();
generateId(); //1
generateId(); //2
function generator(prefix) {
var i = 0;
return function(suffix) {
return prefix + (i++) + (suffix || '');
};
}
var generateId = generator('_');
generateId('_'); //_1_
generateId('@'); //_2@
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
function (baseId) {
return baseId + '-' + Math.random().toString(16).slice(2);
}
const uid = function(){
return Date.now().toString(36) + Math.random().toString(36).substr(2);
}
npm install uuid
import { v4 as uuidv4 } from 'uuid';
const { v4: uuidv4 } = require('uuid');
uuidv4();
// This will output something like: 9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d
function generateId() {
return Math.random().toString(36).substring(2) + (new Date()).getTime().toString(36);
}
console.log(generateId())
const uid = () =>
String(
Date.now().toString(32) +
Math.random().toString(32) +
Math.random().toString(32)
).replace(/\./g, '')
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}`
)
import { nanoid } from 'nanoid'
const id = nanoid() // "Uakgb_J5m9g-0JDMbcJqLJ"
const id = nanoid(10) // "jcNqc0UAWK"
import { v4 as uuidv4 } from 'uuid';
const id= uuidv4(); // quite big id
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())
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
...