简体   繁体   中英

Creating unique id in for loop

I should mention that this will be going into a database so it truly needs to be unique. I need to define the id before it enters the database no questions asked.

for (var i = 0; i < obj.length; i++) {
    var id = Date.now();
    console.log(id);
}

The problem is, this is the output:

1428356251606
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
1428356251607
...

I was thinking of using Math.random() but it might in the name of all the Norse gods actually hit the same number twice.

Any idea of how to make this truly unique while sustaining the speed of the for loop?

You should use i . i is guaranteed to be unique for every iteration of your loop.

Depending on how long lasting you want the uniqueness of your ID to be, you can add another unique compound to the ID ( Date.now() is a good candidate, because it's guaranteed to be unique across different runs on the same machine at different times).

How about

var id = Date.now();
for (var i = 0; i < obj.length; i++) {
    console.log(id+i);
}

You can force iterate until the ids are repeating

var lastGenerated = 0;
var id = 0;
for (var i = 0; i < obj.length; i++) {
    do{
       id = Date.now();
    }while(lastGenerated == id);
    lastGenerated = id;
    console.log(id);
}

or you can make like bellow

var seed = Date.now() * 1000;
for (var i = 0; i < obj.length; i++) {
    var id = seed + i;
    console.log(id);
}

A good solution is create a object to manager the id's ...

(function(w){

   var __id = Date.now();

   function ID(){   }

   ID.prototype.next = function(){

       return ++__id;

   };

   w.ID = new ID();

}(window));





for(var i = 0; i < obj.length; i++){

    var id = ID.next();
    console.log(id);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM