有没有Java集合中的数据结构? [英] Is there a data structure like the Java Set in JavaScript?

查看:99
本文介绍了有没有Java集合中的数据结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用可以用于存储ID数量的JavaScript中的数据结构。我应该能够检查该集合中是否存在一个密钥,就像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

但是,如果你只需要存储字符串,你可以通过将set成员存储为普通Object的属性名称来更简单地做一些事情。例如:

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;
    };
}

有关实现的注释: val 是每个集合唯一的 StringSet 实现内部使用的对象。比较属性名称组成的对象的属性值( setObj )与 val 不同, code> hasOwnProperty()检查并保证只添加到集合中的字符串将显示在中。

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"]

这篇关于有没有Java集合中的数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆