javascript中的对象集

2022-01-17 00:00:00 data-structures object set javascript

我想在 Javascript 中有一组对象.也就是只包含唯一对象的数据结构.

I'd like to have a set of objects in Javascript. That is, a data structure that contains only unique objects.

通常建议使用属性,例如myset["key"] = true.但是,我需要将键作为对象.我读过 Javascript 将属性名称转换为字符串,所以我想我不能使用 myset[myobject] = true.

Normally using properties is recommended, e.g. myset["key"] = true. However, I need the keys to be objects. I've read that Javascript casts property names to strings, so I guess I can't use myset[myobject] = true.

我可以使用数组,但我需要比 O(n) 性能更好的东西来添加、查找和删除项目.

I could use an array, but I need something better than O(n) performance for adding, finding and removing items.

它需要能够仅通过引用来区分对象,因此给出:

It needs to be able to tell objects apart by reference only, so given:

var a = {};
var b = {};

那么 ab 应该都可以添加,因为它们是单独的对象.

then both a and b should be able to be added, because they're separate objects.

基本上,我喜欢 C++ 的 std::set 之类的东西,它可以存储 Javascript 对象.有什么想法吗?

Basically, I'm after something like C++'s std::set, that can store Javascript objects. Any ideas?

推荐答案

ES6提供了原生的设置:

ES6 provides a native Set:

let s = new Set();
let a = {};
let b = {};

s.add(a);

console.log(s.has(a));  // true
console.log(s.has(b));  // false

相关文章