Is there a data structure like the Java Set in JavaScript?(JavaScript 中是否有类似 Java Set 的数据结构?)
问题描述
我想在 JavaScript 中使用可用于存储 ID 数量的数据结构.我应该能够检查该集合中是否已经存在某个键,例如 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
但是,如果您只需要存储字符串,您可以通过将集合成员存储为普通对象的属性名称来做一些更简单的事情.例如:
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
进行比较,无需进行 hasOwnProperty()
检查和保证只有添加到集合中的字符串才会显示在 values
中.
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"]
这篇关于JavaScript 中是否有类似 Java Set 的数据结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:JavaScript 中是否有类似 Java Set 的数据结构?
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01