admin管理员组

文章数量:1244271

I need to get unique random number in javascript (or Typescript).

At this moment I use this code:

var id = -((new Date()).getTime() & 0xffff);

It returns me numbers like -13915 or -28806 ...

It works most of the time but I am having problems when this code is executed in promises (so nearly multiple times at the same time). Then sometimes I got two identical id.

Is there any solution to get unique random numbers in any case ?

I need to get unique random number in javascript (or Typescript).

At this moment I use this code:

var id = -((new Date()).getTime() & 0xffff);

It returns me numbers like -13915 or -28806 ...

It works most of the time but I am having problems when this code is executed in promises (so nearly multiple times at the same time). Then sometimes I got two identical id.

Is there any solution to get unique random numbers in any case ?

Share Improve this question edited Jun 29, 2019 at 15:26 James A Mohler 11.1k15 gold badges50 silver badges76 bronze badges asked Apr 3, 2019 at 8:49 BronzatoBronzato 9,34230 gold badges124 silver badges227 bronze badges 7
  • This is not C where you have to use time as seed. You can use Math.random() (which is probably time-seeded too, but it's way better than your approach) – Christian Vincenzo Traina Commented Apr 3, 2019 at 8:53
  • Possible duplicate of Unique (non-repeating) random numbers in O(1)? – VLAZ Commented Apr 3, 2019 at 8:55
  • Also relevant: stackoverflow./questions/2380019/… althought the accepted answer is not the best. – VLAZ Commented Apr 3, 2019 at 8:56
  • @CristianTraìna Math.random() is not guaranteed to give you unique numbers. I really don't know why this needs to be repeated so many times... – VLAZ Commented Apr 3, 2019 at 8:57
  • This will deal with uniqueness Create GUID / UUID in JavaScript?, then you can transform it to a number if you need another format, but I think the uniqueness spirit should e from overthere ;) – sjahan Commented Apr 3, 2019 at 9:02
 |  Show 2 more ments

5 Answers 5

Reset to default 5

There are many examples around internet. You can start with using Math.random() . For example: generate random number between 1 and 100

Math.floor((Math.random() * 100) + 1);

Just keep in mind that it is not truly random; it is not cryptographically secure. You should probably look into libraries if you need that

Create a function that returns a unique number:

let numbers = [];

const uniqueNumber = (maxVal) => {
   const number = Math.floor((Math.random() * maxVal) + 1);
   if (!numbers.includes(number)) {
      numbers.push(number);
      return number;
   } else if (numbers.length - 1 !== maxVal) {
      uniqueNumber(maxVal);
   }
}

const randomNumber = uniqueNumber(100);
console.log(numbers) // returns all unique numbers

This will return a unqiue number between 1 and 100. It also stops at the max length.

You can use the package uuid:

const uuidv4 = require('uuid/v4');
uuidv4(); // ⇨ '10ba038e-48da-487b-96e8-8d3b99b6d18a'

Notice: It is a number (a 128-bit number) but it is too big to be used as a JavaScript number. You have to keep it as a string.

If you need it on the browser, I suggest to generate the identifier from an API exposed on your back-end. Implementations of UUID exist in most of languages. The npm package will work on browsers but then it uses a fallback to Math.random, which is not secure.

See also: Universally unique identifier.

var datetimestamp = Date.now() + Math.random().toString(36).substr(2, 9);

  1. Math.random() in itself should be safe enough, what with 64-bit numbers. Even with imperfect generator, the chances of hitting the same number twice are minuscule.

  2. If you're after specifically integers, then multiply Math.random() by something BIG, like Number.MAX_SAFE_INTEGER.

  3. To be perfectly safe, you can always store an array of already used ids, and write a function that draws as long as gets a new unique number, pushes it into array, and returns the value. Enclose all that functionality inside a single object/function/class, to keep it neat.

本文标签: Generate unique random numbers in javascript or typescriptStack Overflow