可以在JavaScript中传递句柄到类实例吗?



我是JavaScript新手。我有一个NodeJS express应用程序,它创建了一个类的实例数组。我想为客户端提供一个实例的句柄,这样服务器就不必为每个API调用通过ID找到实例。当实例被删除时,数组索引可能会改变。有干净利落的方法吗?

不使用数组,而是考虑使用Map或对象,因为它们的键查找是次线性的(并且比使用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

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

使用这种方法也不需要担心重新索引。

最新更新