JavaScript 中是否有类似 Java Set 的数据结构?

2022-01-17 00:00:00 set javascript java dojo

我想在 JavaScript 中使用可用于存储 ID 数量的数据结构.我应该能够检查该集合中是否已经存在某个键,例如 Java 集合.

I want to use a data structure in JavaScript that can be used to store number of IDs. I should be able to check if a key already exists in that set, something like Java Sets.

我想实现以下相同的行为(此代码是 Java 代码):

I want to achive same behaviours as follows (this code is in Java):

Set<String> st = new HashSet<String>();
//add elemets

if(st.contains("aks") ){
  //do something
}

我想要一个与上述代码等效的 JavaScript/dojo.

I want a JavaScript/dojo equivalent of the above code.

推荐答案

我已经编写了一个 JavaScript HashSet 实现,它可以做你想做的事情并允许任何对象成为集合的成员:http://code.google.com/p/jshashtable

I've written a JavaScript HashSet implementation that does what you want and allows any object to be a member of the set: http://code.google.com/p/jshashtable

但是,如果您只需要存储字符串,您可以通过将集合成员存储为普通对象的属性名称来做一些更简单的事情.例如:

However, if you just need to store strings, you could do something more simply by storing set members as property names of a normal Object. For example:

function StringSet() {
    var setObj = {}, val = {};

    this.add = function(str) {
        setObj[str] = val;
    };

    this.contains = function(str) {
        return setObj[str] === val;
    };

    this.remove = function(str) {
        delete setObj[str];
    };

    this.values = function() {
        var values = [];
        for (var i in setObj) {
            if (setObj[i] === val) {
                values.push(i);
            }
        }
        return values;
    };
}

关于实现的说明:valStringSet 实现内部使用的对象,每个集合都是唯一的.将属性名称构成集合 (setObj) 的对象的属性值与 val 进行比较,无需进行 hasOwnProperty() 检查和保证只有添加到集合中的字符串才会显示在 values 中.

A note about the implementation: val is an object used internally by the StringSet implementation that is unique to each set. Comparing property values of the object whose property names make up the set (setObj) against val eliminates the need for a hasOwnProperty() check and guarantees that only strings that have been added to the set will show up in values.

示例用法:

var set = new StringSet();
set.add("foo");
set.add("bar");

alert(set.contains("foo")); // true
alert(set.contains("baz")); // false

set.values(); // ["foo", "bar"], though not necessarily in that order
set.remove("foo");
set.values(); // ["bar"]

相关文章