我正在使用JavaScript。我想存储具有以下属性的唯一,无序字符串值的列表:
- 快速询问“列表中是否有A”的方法?
- 一种快速的方法(如果列表中存在A,则从列表中删除A)
- 一种快速的方法“将A添加到列表(如果尚不存在)”。
我真正想要的是一套。有什么建议以最佳方式模仿JavaScript中的集合吗?
这个问题建议使用Object,其键存储属性,并且所有值都设置为true:这是明智的方法吗?
我正在使用JavaScript。我想存储具有以下属性的唯一,无序字符串值的列表:
我真正想要的是一套。有什么建议以最佳方式模仿JavaScript中的集合吗?
这个问题建议使用Object,其键存储属性,并且所有值都设置为true:这是明智的方法吗?
Answers:
如果要在支持ES6的环境中进行编程(例如,node.js,这是您需要的具有ES6功能的特定浏览器,或者为您的环境转换ES6代码),则可以使用Set
ES6中内置的对象。它具有非常好的功能,可以在您的环境中直接使用。
对于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;
Object.keys(obj)
。
obj.hasOwnProperty(prop)
用于会员资格检查。使用Object.prototype.hasOwnProperty.call(obj, prop)
代替,即使“ set”包含value,它也可以工作"hasOwnProperty"
。
您可以创建没有任何属性的对象,例如
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
set = {}
它,它将继承Object的所有属性(例如toString
),因此您必须hasOwnProperty
在if (A in set)
set[A]=true
要添加的每个元素都具有语句,而不仅仅是一个初始化程序?
s = Object.create(null);s["thorben"] = true;ss = Object.create(s)
在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)中的运行引用?我对此很感兴趣
我已经开始执行Sets的实现,该实现目前可以很好地与数字和字符串配合使用。我的主要重点是差异操作,因此我试图使其尽可能高效。欢迎叉和代码审查!
我刚刚注意到d3.js库具有集,地图和其他数据结构的实现。我不能争论它们的效率,但是从它是一个受欢迎的图书馆这一事实来看,它一定是您所需要的。
文档在这里
为了方便起见,我从链接中复制(前三个功能是您感兴趣的那些)
构造一个新集合。如果指定了array,则将给定的字符串值数组添加到返回的集合中。
当且仅当此集合具有指定值字符串的条目时,才返回true。
将指定的值字符串添加到此集合。
如果集合包含指定的值字符串,则将其删除并返回true。否则,此方法不执行任何操作并返回false。
返回此集合中的字符串值的数组。返回值的顺序是任意的。可用作计算一组字符串的唯一值的便捷方法。例如:
d3.set([[“ foo”,“ bar”,“ foo”,“ baz”])。values(); //“ foo”,“ bar”,“ baz”
为该集中的每个值调用指定的函数,并将该值作为参数传递。函数的this上下文就是这个集合。返回未定义。迭代顺序是任意的。
当且仅当此集合具有零值时,才返回true。
返回此集合中的值数。