在 JavaScript 中模仿集合?
我在 JavaScript 工作。我想存储具有以下属性的唯一无序字符串值的列表:
- 问“A在列表中”的快速方法?
- 一种快速执行“如果列表中存在A,则从列表中删除A”的快速方法
- 一种快速完成“如果A尚不存在,则将其添加到列表中”的快速方法。
我真正想要的是一套。对于在JavaScript中模仿集合的最佳方法有什么建议吗?
这个问题建议使用对象,键存储属性,值都设置为 true:这是一种明智的方法吗?
我在 JavaScript 工作。我想存储具有以下属性的唯一无序字符串值的列表:
我真正想要的是一套。对于在JavaScript中模仿集合的最佳方法有什么建议吗?
这个问题建议使用对象,键存储属性,值都设置为 true:这是一种明智的方法吗?
如果要在支持 ES6 的环境中(如 node.js、具有所需 ES6 功能的特定浏览器或为您的环境转译 ES6 代码)中编程,则可以使用内置于 ES6 中的 Set
对象。它具有非常好的功能,可以在您的环境中按原样使用。
对于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 对象。它现在在某些浏览器中实现。由于浏览器可用性随时间而变化,因此您可以查看此 ES6 兼容性表中的 行,以查看浏览器可用性的当前状态。Set
内置 Set 对象的一个优点是,它不会像 Object 那样将所有键强制为字符串,因此您可以将 5 和“5”作为单独的键。而且,您甚至可以直接在集合中使用对象,而无需字符串转换。这是一篇文章,描述了一些关于 Set 对象的功能和 MDN 的文档。
我现在已经为ES6集对象编写了一个polyfill,因此您可以立即开始使用它,如果浏览器支持它,它将自动延迟到内置的set对象。这样做的好处是,您正在编写与ES6兼容的代码,这些代码将一直工作到IE7。但是,也有一些缺点。ES6集合接口利用了ES6迭代器,因此您可以执行类似操作,它将自动为您迭代该集合。但是,这种类型的语言功能不能通过polyfill实现。您仍然可以在不使用新的ES6语言功能的情况下迭代ES6集,但坦率地说,如果没有新的语言功能,它并不像我在下面包含的其他设置界面那样方便。for (item of mySet)
在查看了两者之后,您可以决定哪一个最适合您。ES6套装polyfill在这里:https://github.com/jfriend00/ES6-Set。
仅供参考,在我自己的测试中,我注意到Firefox v29 Set实现在规范的当前草案上并不完全最新。例如,您不能像规范描述的那样链接方法调用,而我的 polyfill 支持。这可能是一个正在进行的规范问题,因为它尚未最终确定。.add()
预建集对象:如果想要一个已构建的对象,该对象具有可在任何浏览器中使用的集的操作方法,则可以使用一系列不同的预构建对象来实现不同类型的集。有一个 miniSet 是实现 set 对象基础知识的小代码。它还具有一个功能更丰富的集合对象和几个派生,包括字典(让您为每个键存储/检索一个值)和一个对象集(让您保留一组对象 - 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;
您可以创建一个没有属性的对象,例如
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