您能在JavaScript中向类实例传递句柄吗?

您能在JavaScript中向类实例传递句柄吗?,javascript,class,instance,Javascript,Class,Instance,我对JavaScript非常陌生。我有一个NodeJS express应用程序,它创建一个类的实例数组。我想为客户机提供一个实例句柄,这样服务器就不必为每个API调用按ID查找实例。删除实例时,数组索引可能会更改。有没有一种干净的方法可以做到这一点?与其使用数组,不如考虑使用一个映射或对象,对于该映射或对象,键查找是次线性的(并且比使用数组的findIndex要快得多)。例如,而不是 const handles = []; // when you need to add an item: ha

我对JavaScript非常陌生。我有一个NodeJS express应用程序,它创建一个类的实例数组。我想为客户机提供一个实例句柄,这样服务器就不必为每个API调用按ID查找实例。删除实例时,数组索引可能会更改。有没有一种干净的方法可以做到这一点?

与其使用数组,不如考虑使用一个映射或对象,对于该映射或对象,键查找是次线性的(并且比使用数组的
findIndex
要快得多)。例如,而不是

const handles = [];

// when you need to add an item:
handles.push(new Handle(1234));

// when you need to retrieve an item:
const handle = handles.find(obj => obj.id === id)
// will be undefined if no such handle exists yet

也不必担心用这种方法重新编制索引。

foo=newfoo();someFn(foo)
const handles = new Map();

// when you need to add an item:
handles.set(1234, new Handle(1234));

// when you need to retrieve an item
const handle = handles.get(id);
// will be undefined if no such handle exists yet