在 javascript/jQuery 中设置 Java 的数据结构

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3042886/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 03:04:11  来源:igfitidea点击:

Set data structure of Java in javascript/jQuery

javascriptjquery

提问by Suvonkar

Is there any way to create Set data structure(Unique Collections) like java in javascript?

有没有办法在javascript中像java一样创建Set数据结构(Unique Collections)?

回答by Matthew Flaschen

For a set of strings, I would just use a object with the value true.

对于一组字符串,我只会使用值为 true 的对象。

var obj = {};
obj["foo"] = true;
obj["bar"] = true;

if(obj["foo"])
{
  // foo in set
}

This is basically how HashSet works in Java, assuming the JavaScript object is implemented as a hashtable (which is typical).

这基本上是 HashSet 在 Java 中的工作方式,假设 JavaScript 对象实现为哈希表(这是典型的)。

回答by Tim Down

I have written a JavaScript implementation of a hash set that is similar to Java's HashSet. It allows any object (not just strings) to be used as a set member. It's based on the keys of a hash table.

我编写了一个类似于 Java 的 HashSet 的哈希集的 JavaScript 实现。它允许将任何对象(不仅仅是字符串)用作集合成员。它基于哈希表的键。

http://code.google.com/p/jshashtable/downloads/list

http://code.google.com/p/jshashtable/downloads/list

Documentation will follow shortly, I promise. For now, the source should give you the API pretty clearly, and here's an example:

我保证很快就会有文档。现在,源代码应该非常清楚地为您提供 API,这是一个示例:

var s = new HashSet();
var o1 = {name: "One"}, o2 = {name: "Two"};
s.add(o1);
s.add(o2);
s.add(o2);
s.values(); // Array containing o1 and a single reference to o2

回答by msanjay

Well though it seemed to be a common problem, and I found what seemed to be a good Set class on the netthat supports objects, I wanted a simpler one and ended up writing one myself... in case anyone else finds it useful...

好吧,虽然这似乎是一个常见问题,而且我在支持对象的网络上发现了一个看起来不错的 Set 类,但我想要一个更简单的类,最终自己编写了一个......以防其他人发现它有用。 ..

/**
 * A Javascript Class that represents a set of unique values
 * 
 * Usage:
 * 
 * var s = new jsSet();
 * 
 * s.add('a1'); s.add('a2');
 * 
 * s.list(); >> ['a1','a2']
 * 
 * s.remove('a1'); s.list(); >> ['a2']
 * 
 * s.contains('a1') >> false
 * 
 * s.contains('a2') >> true
 * 
 * can be chained
 * s.add(null).add('hello');
 * 
 * add array
 * s.addAll([ null, 'a', 'b' ]);
 * 
 * remove array
 * s.addAll([ null, 'a', 'b' ]);
 * 
 * retrieve the elements as a list
 * s.list();
 * 
 * size of the set
 * s.size();
 * 
 */
function jsSet() {

    // null can also be an element of the set, but needs
    // a separate indication to differentiate it from
    // the string "null" as well
    this.isNullAdded = false;

    // private member variable hence no 'this'
    var map = {};

    //  Scope for optimization
    //  could be cached instead of generating each time
    //  this.uniqueList = [];

    //  returns true if the element is in this set, false otherwise
    this.contains = function(key) {

        if (key === null)
            return this.isNullAdded;
        else if (key === undefined)
            return false;
        else
            return map[key] ? true : false;
    };

    //  adds the element to the set
    this.add = function(val) {

        if (val === null)
            this.isNullAdded = true;
        else if (val !== undefined)
            map[val] = true;
        return this;
    };

    //  adds all the elements of the array to the set
    this.addAll = function(val) {

        if (val !== null && val !== undefined && val instanceof Array) {
            for ( var idx = 0; idx < val.length; idx++) {
                this.add(val[idx]);
            }
        }
        return this;
    };

    //  removes the specified element from the set
    this.remove = function(val) {
        if (val === null)
            this.isNullAdded = false;
        else if (val !== undefined)
            delete map[val];
        return this;
    };

    //  removes all the element in the array from the set
    this.removeAll = function(val) {

        if (val !== null && val !== undefined && val instanceof Array) {
            for ( var idx = 0; idx < val.length; idx++) {
                console.log('val: %s:%s', idx, val[idx]);
                this.remove(val[idx]);
            }
        }
        return this;
    };

    //  empties the set of all values
    this.clear = function() {

        this.isNullAdded = false;
        map = {};
        return this;
    };

    //  returns the number of elements in the set
    this.size = function() {

        return this.list().length;
    };

    //  returns true if the set is empty, false otherwise
    this.isEmpty = function() {

        return this.list().length > 0? false: true;
    };

    //  returns the elements of the set as a list
    this.list = function() {
        var arr = [];

        if (this.isNullAdded)
            arr.push(null);

        for (o in map) {
            // protect from inherited properties such as
            //  Object.prototype.test = 'inherited property';
            if (map.hasOwnProperty(o))
                arr.push(o);
        }
        return arr;
    };
};

回答by PhoneixS

In modern browsers, I would use a Map using only the keys' methods. For example:

在现代浏览器中,我会只使用键的方法来使用 Map。例如:

  • New set: let mySet = new Map();
  • Add element: mySet.set(element, 1)
  • Remove element: mySet.delete(element)
  • Contains element: mySet.has(element)
  • 新套装: let mySet = new Map();
  • 添加元素: mySet.set(element, 1)
  • 删除元素: mySet.delete(element)
  • 包含元素: mySet.has(element)

You can make your own wrapper if you don't want to see the Map implementation. This approach is how Java HashSet is implemented, it uses a HashMap and only uses the key methods.

如果您不想看到 Map 实现,您可以制作自己的包装器。这种方法是 Java HashSet 的实现方式,它使用 HashMap 并且只使用关键方法。