Create a unique object id using javascript

The objects that I use on the client side need a unique identifier. My array of objects is very small, usually 4 elements, no more.

I use this:

export class MyItem { uniqueObjectIdentifier: number; constructor(obj) { this.uniqueObjectIdentifier = Math.random(); } } 

Is there something, possibly javascript or angular internal, that I can access instead of the handcrafted property?

+5
source share
2 answers

You can use Symbol .

Each symbol value returned from Symbol () is unique.

 export class MyItem { uniqueObjectIdentifier: symbol; constructor(obj) { this.uniqueObjectIdentifier = Symbol(); } } 

If browser support does not allow the use of a symbol, you can use the link to the object.

 export class MyItem { uniqueObjectIdentifier: object; constructor(obj) { this.uniqueObjectIdentifier = {}; } } 
+7
source

In TypeScript, you can do this:

 export class MyItem { static currentId: number = 0; uniqueObjectIdentifier: number; constructor(obj) { this.uniqueObjectIdentifier = MyItem.currentId++; } } 

In JavaScript ES6:

 export class MyItem { constructor(obj) { this.uniqueObjectIdentifier = MyItem.currentId++; } } MyItem.currentId = 0; 

Or you can use an extended variable with scope to hold a counter:

 let currentId = 0; export class MyItem { constructor(obj) { this.uniqueObjectIdentifier = currentId++; } } 

Thus, currentId cannot be changed from outside the module.

+1
source

Source: https://habr.com/ru/post/1269765/


All Articles