在JavaScript中模仿集合?


220

我正在使用JavaScript。我想存储具有以下属性的唯一,无序字符串值的列表:

  1. 快速询问“列表中是否有A”的方法?
  2. 一种快速的方法(如果列表中存在A,则从列表中删除A)
  3. 一种快速的方法“将A添加到列表(如果尚不存在)”。

我真正想要的是一套。有什么建议以最佳方式模仿JavaScript中的集合吗?

这个问题建议使用Object,其键存储属性,并且所有值都设置为true:这是明智的方法吗?



Answers:


262

如果要在支持ES6的环境中进行编程(例如,node.js,这是您需要的具有ES6功能的特定浏览器,或者为您的环境转换ES6代码),则可以使用SetES6中内置对象。它具有非常好的功能,可以在您的环境中直接使用。


对于ES5环境中的许多简单事物,使用Object效果很好。如果obj是您的对象,并且A是一个具有要在集合中操作的值的变量,则可以执行以下操作:

初始化代码:

// create empty object
var obj = {};

// or create an object with some items already in it
var obj = {"1":true, "2":true, "3":true, "9":true};

问题1:A在列表中:

if (A in obj) {
    // put code here
}

问题2:如果存在,请从列表中删除“ A”:

delete obj[A];

问题3:如果尚未在列表中添加“ A”

obj[A] = true;

为了完整起见,使用以下方法测试是否A在列表中会更加安全:

if (Object.prototype.hasOwnProperty.call(obj, A))
    // put code here
}

因为基础对象上的内置方法和/或属性(例如constructor属性)之间可能存在冲突。


ES6上的侧栏:ECMAScript 6或ES 2015 的当前工作版本具有内置的Set对象。现在已在某些浏览器中实现。由于浏览器的可用性随时间变化的,你可以看看线Set此ES6兼容性表,查看浏览器可用性的当前状态。

内置Set对象的一个​​优点是,它不像Object那样将所有键都强制转换为字符串,因此您可以将5和“ 5”分别作为单独的键。而且,您甚至可以直接在集合中使用对象,而无需进行字符串转换。下面是一篇文章,描述了一些功能和MDN的文档设置对象。

我现在为ES6设置对象编写了一个polyfill,因此您现在就可以开始使用它,如果浏览器支持,它将自动遵从内置设置对象。这样做的好处是,您正在编写与ES6兼容的代码,这些代码将一直工作到IE7。但是,还有一些缺点。ES6 set接口利用了ES6迭代器,因此您可以做类似的事情for (item of mySet),它将为您自动遍历set6。但是,这种语言功能无法通过polyfill实现。您仍然可以在不使用新ES6语言功能的情况下迭代ES6集,但是坦率地说,在没有新语言功能的情况下,它不如我在下面包括的其他集界面那样方便。

查看两者后,您可以决定哪一个最适合您。ES6集合polyfill在这里:https : //github.com/jfriend00/ES6-Set

仅供参考,在我自己的测试中,我注意到Firefox v29 Set实施不是最新的规范草案。例如,您不能.add()像规范说明和我的polyfill支持那样链接方法调用。这可能是运动规范的问题,因为它尚未最终确定。


预先构建的Set对象:如果想要一个已经构建的对象,该对象具有可在任何浏览器中使用的对集合进行操作的方法,则可以使用实现不同类型集合的一系列不同的预先构建的对象。有一个miniSet,它是一些小的代码,可实现set对象的基础。它还具有功能更丰富的set对象和几个派生对象,包括Dictionary(让您为每个键存储/检索一个值)和ObjectSet(让您保留一组对象-JS对象或DOM对象,您可以在其中提供为每个键生成唯一键的函数,否则ObjectSet会为您生成键)。

这是miniSet的代码副本(最新代码在github上)。

"use strict";
//-------------------------------------------
// Simple implementation of a Set in javascript
//
// Supports any element type that can uniquely be identified
//    with its string conversion (e.g. toString() operator).
// This includes strings, numbers, dates, etc...
// It does not include objects or arrays though
//    one could implement a toString() operator
//    on an object that would uniquely identify
//    the object.
// 
// Uses a javascript object to hold the Set
//
// This is a subset of the Set object designed to be smaller and faster, but
// not as extensible.  This implementation should not be mixed with the Set object
// as in don't pass a miniSet to a Set constructor or vice versa.  Both can exist and be
// used separately in the same project, though if you want the features of the other
// sets, then you should probably just include them and not include miniSet as it's
// really designed for someone who just wants the smallest amount of code to get
// a Set interface.
//
// s.add(key)                      // adds a key to the Set (if it doesn't already exist)
// s.add(key1, key2, key3)         // adds multiple keys
// s.add([key1, key2, key3])       // adds multiple keys
// s.add(otherSet)                 // adds another Set to this Set
// s.add(arrayLikeObject)          // adds anything that a subclass returns true on _isPseudoArray()
// s.remove(key)                   // removes a key from the Set
// s.remove(["a", "b"]);           // removes all keys in the passed in array
// s.remove("a", "b", ["first", "second"]);   // removes all keys specified
// s.has(key)                      // returns true/false if key exists in the Set
// s.isEmpty()                     // returns true/false for whether Set is empty
// s.keys()                        // returns an array of keys in the Set
// s.clear()                       // clears all data from the Set
// s.each(fn)                      // iterate over all items in the Set (return this for method chaining)
//
// All methods return the object for use in chaining except when the point
// of the method is to return a specific value (such as .keys() or .isEmpty())
//-------------------------------------------


// polyfill for Array.isArray
if(!Array.isArray) {
    Array.isArray = function (vArg) {
        return Object.prototype.toString.call(vArg) === "[object Array]";
    };
}

function MiniSet(initialData) {
    // Usage:
    // new MiniSet()
    // new MiniSet(1,2,3,4,5)
    // new MiniSet(["1", "2", "3", "4", "5"])
    // new MiniSet(otherSet)
    // new MiniSet(otherSet1, otherSet2, ...)
    this.data = {};
    this.add.apply(this, arguments);
}

MiniSet.prototype = {
    // usage:
    // add(key)
    // add([key1, key2, key3])
    // add(otherSet)
    // add(key1, [key2, key3, key4], otherSet)
    // add supports the EXACT same arguments as the constructor
    add: function() {
        var key;
        for (var i = 0; i < arguments.length; i++) {
            key = arguments[i];
            if (Array.isArray(key)) {
                for (var j = 0; j < key.length; j++) {
                    this.data[key[j]] = key[j];
                }
            } else if (key instanceof MiniSet) {
                var self = this;
                key.each(function(val, key) {
                    self.data[key] = val;
                });
            } else {
                // just a key, so add it
                this.data[key] = key;
            }
        }
        return this;
    },
    // private: to remove a single item
    // does not have all the argument flexibility that remove does
    _removeItem: function(key) {
        delete this.data[key];
    },
    // usage:
    // remove(key)
    // remove(key1, key2, key3)
    // remove([key1, key2, key3])
    remove: function(key) {
        // can be one or more args
        // each arg can be a string key or an array of string keys
        var item;
        for (var j = 0; j < arguments.length; j++) {
            item = arguments[j];
            if (Array.isArray(item)) {
                // must be an array of keys
                for (var i = 0; i < item.length; i++) {
                    this._removeItem(item[i]);
                }
            } else {
                this._removeItem(item);
            }
        }
        return this;
    },
    // returns true/false on whether the key exists
    has: function(key) {
        return Object.prototype.hasOwnProperty.call(this.data, key);
    },
    // tells you if the Set is empty or not
    isEmpty: function() {
        for (var key in this.data) {
            if (this.has(key)) {
                return false;
            }
        }
        return true;
    },
    // returns an array of all keys in the Set
    // returns the original key (not the string converted form)
    keys: function() {
        var results = [];
        this.each(function(data) {
            results.push(data);
        });
        return results;
    },
    // clears the Set
    clear: function() {
        this.data = {}; 
        return this;
    },
    // iterate over all elements in the Set until callback returns false
    // myCallback(key) is the callback form
    // If the callback returns false, then the iteration is stopped
    // returns the Set to allow method chaining
    each: function(fn) {
        this.eachReturn(fn);
        return this;
    },
    // iterate all elements until callback returns false
    // myCallback(key) is the callback form
    // returns false if iteration was stopped
    // returns true if iteration completed
    eachReturn: function(fn) {
        for (var key in this.data) {
            if (this.has(key)) {
                if (fn.call(this, this.data[key], key) === false) {
                    return false;
                }
            }
        }
        return true;
    }
};

MiniSet.prototype.constructor = MiniSet;

16
这就解决了问题,但要明确地说,此实现不适用于除整数或字符串之外的其他事物。
mkirk

3
@mkirk-是的,您要在集合中索引的项目必须具有可以作为索引键的字符串表示形式(例如,它可以是字符串或具有唯一描述该项目的toString()方法)。
jfriend00 2012年

4
要获取列表中的项目,可以使用Object.keys(obj)
Blixt 2012年

3
@Blixt- Object.keys()需要IE9,FF4,Safari 5,Opera 12或更高版本。有旧版本浏览器一个填充工具在这里
jfriend00

1
不要obj.hasOwnProperty(prop)用于会员资格检查。使用Object.prototype.hasOwnProperty.call(obj, prop)代替,即使“ set”包含value,它也可以工作"hasOwnProperty"
davidchambers

72

您可以创建没有任何属性的对象,例如

var set = Object.create(null)

它可以作为一个集合,消除了使用的需要hasOwnProperty


var set = Object.create(null); // create an object with no properties

if (A in set) { // 1. is A in the list
  // some code
}
delete set[a]; // 2. delete A from the list if it exists in the list 
set[A] = true; // 3. add A to the list if it is not already present

很好,但不确定为什么您会说“消除了使用hasOwnProperty的需要”
blueFast 2014年

13
如果您只使用set = {}它,它将继承Object的所有属性(例如toString),因此您必须hasOwnPropertyif (A in set)
ThorbenCroisé2014年

6
我不知道有可能创建一个完全空的对象。谢谢,您的解决方案非常优雅。
blueFast

1
有趣,但是这样做的缺点是,您必须对set[A]=true要添加的每个元素都具有语句,而不仅仅是一个初始化程序?
vogomatix 2014年

1
不确定您的意思是什么,但是如果您要指的是通过已存在的集合初始化集合,则可以按照s = Object.create(null);s["thorben"] = true;ss = Object.create(s)
ThorbenCroisé2014年

23

从ECMAScript 6开始,Set数据结构是一个内置功能。与node.js版本的兼容性可以在这里找到。


4
您好,为清楚起见-现在是2014年,是否仍可以在Chrome浏览器中进行实验?如果不是,请编辑您的答案吗?谢谢
KarelBílek'14

1
是的,它仍适用于Chrome。我相信,到2014年底,应该正式发布ECMAScript时,它将得到支持。然后,我将相应地更新我的答案。
hymloth

OK,谢谢回答!(JavaScript答案很快就会过时。)
KarelBílek2014年

1
@Val in不起作用,因为Set对象没有其元素作为属性,这很糟糕,因为集合可以具有任何类型的元素,但是属性是字符串。您可以使用hasSet([1,2]).has(1)
Oriol 2014年


14

在ES6版本的Javascript中,您已经内置了set类型(请检查与浏览器的兼容性)。

var numbers = new Set([1, 2, 4]); // Set {1, 2, 4}

要将元素添加到集合中,您只需使用.add(),它将运行O(1)并添加到集合中(如果元素不存在)或不执行任何操作(如果元素已经存在)。您可以在那里添加任何类型的元素(数组,字符串,数字)

numbers.add(4); // Set {1, 2, 4}
numbers.add(6); // Set {1, 2, 4, 6}

检查集合中的元素数量,只需使用即可.size。也可以在O(1)

numbers.size; // 4

要从集合中删除元素,请使用.delete()。如果该值在那里(并已删除),则返回true;如果该值不存在,则返回false。也可以在中运行O(1)

numbers.delete(2); // true
numbers.delete(2); // false

检查元素是否存在于集合中,请使用.has(),如果元素在集合中,则返回true,否则返回false。也可以在中运行O(1)

numbers.has(3); // false
numbers.has(1); // true

除了您想要的方法外,还有一些其他方法:

  • numbers.clear(); 只会从集合中删除所有元素
  • numbers.forEach(callback); 按插入顺序迭代集合的值
  • numbers.entries(); 创建所有值的迭代器
  • numbers.keys(); 返回集合的键,该键与 numbers.values()

还有一个Weakset,它仅允许添加对象类型的值。


您能否指向.add()O(1)中的运行引用?我对此很感兴趣
Green Green

10

我已经开始执行Sets的实现,该实现目前可以很好地与数字和字符串配合使用。我的主要重点是差异操作,因此我试图使其尽可能高效。欢迎叉和代码审查!

https://github.com/mcrisc/SetJS


哇,这堂课真疯了!如果我不在CouchDB map / reduce函数中编写JavaScript,我将完全使用它!
portforwardpodcast 2012年

9

我刚刚注意到d3.js库具有集,地图和其他数据结构的实现。我不能争论它们的效率,但是从它是一个受欢迎的图书馆这一事实来看,它一定是您所需要的。

文档在这里

为了方便起见,我从链接中复制(前三个功能是您感兴趣的那些)


  • d3.set([array])

构造一个新集合。如果指定了array,则将给定的字符串值数组添加到返回的集合中。

  • set.has(值)

当且仅当此集合具有指定值字符串的条目时,才返回true。

  • set.add(值)

将指定的值字符串添加到此集合。

  • set.remove(值)

如果集合包含指定的值字符串,则将其删除并返回true。否则,此方法不执行任何操作并返回false。

  • set.values()

返回此集合中的字符串值的数组。返回值的顺序是任意的。可用作计算一组字符串的唯一值的便捷方法。例如:

d3.set([[“ foo”,“ bar”,“ foo”,“ baz”])。values(); //“ foo”,“ bar”,“ baz”

  • set.forEach(功能)

为该集中的每个值调用指定的函数,并将该值作为参数传递。函数的this上下文就是这个集合。返回未定义。迭代顺序是任意的。

  • set.empty()

当且仅当此集合具有零值时,才返回true。

  • set.size()

返回此集合中的值数。


4

是的,这是一种明智的方法-所有对象都是(对于此用例而言)-一堆具有直接访问权限的键/值。

在添加之前,您需要检查它是否已经存在,或者只是需要指示是否存在,再次“添加”它实际上并没有改变任何东西,它只是将其再次设置在对象上。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.