Unique object identifier in javascript Ask Question

Unique object identifier in javascript Ask Question

I need to do some experiment, and I need to use some kind of unique identifier for objects in JavaScript so I can see if they are the same.

I don't want to use equality operators. Instead, I need something like the id() function in Python.

Does something like this exist?

ベストアンサー1

So far as my observation goes, any answer posted here can have unexpected side effects.

In ES2015-compatible enviroment, you can avoid any side effects by using WeakMap.

const id = (() => {
    let currentId = 0;
    const map = new WeakMap();

    return (object) => {
        if (!map.has(object)) {
            map.set(object, ++currentId);
        }

        return map.get(object);
    };
})();

id({}); //=> 1

おすすめ記事