I have a jsfiddle.
obj = {};
obj[0] = 'hej';
obj[1] = 'hopp';
$.each( obj, function( key, value ) {
console.log($.now());
});
$.now()
is the same number in the console.
How can I generate a unique number?
I have a jsfiddle.
obj = {};
obj[0] = 'hej';
obj[1] = 'hopp';
$.each( obj, function( key, value ) {
console.log($.now());
});
$.now()
is the same number in the console.
How can I generate a unique number?
You could have a counter which increments for each object. You could then add this counter to $.now() to make sure it's unique:
jQuery.now()
isn't supposed to give you a unique number, just a " a number representing the current time" (http://api.jquery.com/jQuery.now/). More specifically "the number of milliseconds since 1 January 1970 00:00:00 UTC" (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime).The simplest way to generate a unique identifier depends on the scope the identifier has to be unique in.
1: If the identifier just has to be unique within the scope of the function, a counter as suggested by SteveP would probably do the job best.
2: If the identifier needs to be unique within the scope of your application - and you do not have the possibility to keep track of the assigned identifiers (as in 1) - your job is more difficult. In real-live applications such a scenario could be tackled by combining the timestamp with a random number, along the lines of
This approach doesn't guarantee for true uniqueness of
identifier
though sinceMath.round(Math.random() * 1e10)
could return the same value twice in one millisecond. Depending on how often you generate a string like this, it will be still pretty unlikely you end up with the same string twice.3: If you however aim for "uniqueness across space and time", you could get inspiration from http://www.ietf.org/rfc/rfc4122.txt
It should be noted that pure Javascript implementations like Create GUID / UUID in JavaScript? only work with random numbers as well and will thus not generate truly unique identifiers. For a truly unique identifier across space and time a truly unique element such as a mac-address has to be used as part of the identifier.
Quote from jquery api:
So you basically use
new Date().getTime()
. However getTime() isn't accurate... Interresting quote from this article:In short:
getTime()
isn't that accurate (in some browsers).When you need a random number (as you do), use:
When you need a more formal 'guid', use something like this:
Of course
$.now
just display the current timestamp. to have a random number useMath.random()