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 的数据结构?
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- C++ 和 Java 进程之间的共享内存 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
