Geo*_*ge2 548 javascript dictionary hashtable
我需要使用JavaScript存储一些统计信息,就像我在C#中这样做:
Dictionary<string, int> statistics;
statistics["Foo"] = 10;
statistics["Goo"] = statistics["Goo"] + 1;
statistics.Add("Zoo", 1);
Run Code Online (Sandbox Code Playgroud)
JavaScript中是否有Hashtable
类似的东西Dictionary<TKey, TValue>
?
我怎么能以这种方式存储价值?
Ale*_*vis 535
关联数组:简单来说,关联数组使用字符串而不是整数作为索引.
用.创建一个对象
var dictionary = {};
Run Code Online (Sandbox Code Playgroud)
Javascript允许您使用以下语法向对象添加属性:
Object.yourProperty = value;
Run Code Online (Sandbox Code Playgroud)
另一种语法是:
Object["yourProperty"] = value;
Run Code Online (Sandbox Code Playgroud)
如果还可以使用以下语法创建值对象映射的键
var point = { x:3, y:2 };
point["x"] // returns 3
point.y // returns 2
Run Code Online (Sandbox Code Playgroud)
您可以使用for..in循环结构迭代关联数组,如下所示
for(var key in Object.keys(dict)){
var value = dict[key];
/* use key/value for intended purpose */
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*cco 428
var associativeArray = {};
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
Run Code Online (Sandbox Code Playgroud)
如果您来自面向对象语言,请查看本文.
ror*_*ryf 131
除非您有特殊原因,否则只需使用普通对象即可.可以使用散列表样式语法引用Javascript中的对象属性:
var hashtable = {};
hashtable.foo = "bar";
hashtable['bar'] = "foo";
Run Code Online (Sandbox Code Playgroud)
现在可以将两者foo
和bar
元素引用为:
hashtable['foo'];
hashtable['bar'];
// or
hashtable.foo;
hashtable.bar;
Run Code Online (Sandbox Code Playgroud)
当然这意味着你的密钥必须是字符串.如果它们不是字符串,则会在内部转换为字符串,因此它可能仍然有效,YMMV.
Vit*_*nko 129
所有现代浏览器都支持javascript Map对象.有几个原因使得使用Map比Object更好:
- Object有一个原型,因此地图中有默认键.
- Object的键是字符串,它们可以是Map的任何值.
- 您可以轻松获取地图的大小,同时必须跟踪对象的大小.
例:
var myMap = new Map();
var keyObj = {},
keyFunc = function () {},
keyString = "a string";
myMap.set(keyString, "value associated with 'a string'");
myMap.set(keyObj, "value associated with keyObj");
myMap.set(keyFunc, "value associated with keyFunc");
myMap.size; // 3
myMap.get(keyString); // "value associated with 'a string'"
myMap.get(keyObj); // "value associated with keyObj"
myMap.get(keyFunc); // "value associated with keyFunc"
Run Code Online (Sandbox Code Playgroud)
如果希望对未从其他对象引用的键进行垃圾回收,请考虑使用WeakMap而不是Map.
Sho*_*og9 49
由于JS中的每个对象都表现得像 - 并且通常被实现为 - 一个哈希表,我只是去...
var hashSweetHashTable = {};
Run Code Online (Sandbox Code Playgroud)
Raj*_*Raj 20
所以在C#代码看起来像:
Dictionary<string,int> dictionary = new Dictionary<string,int>();
dictionary.add("sample1", 1);
dictionary.add("sample2", 2);
Run Code Online (Sandbox Code Playgroud)
要么
var dictionary = new Dictionary<string, int> {
{"sample1", 1},
{"sample2", 2}
};
Run Code Online (Sandbox Code Playgroud)
在JavaScript中
var dictionary = {
"sample1": 1,
"sample2": 2
}
Run Code Online (Sandbox Code Playgroud)
C#dictionary对象包含有用的方法,比如dictionary.ContainsKey()
在JavaScript中我们可以使用hasOwnProperty
类似的方法
if (dictionary.hasOwnProperty("sample1"))
console.log("sample1 key found and its value is"+ dictionary["sample1"]);
Run Code Online (Sandbox Code Playgroud)
Tim*_*own 18
如果你需要你的键是任何对象而不是字符串,那么你可以使用我的jshashtable.
我创建它来实现一些问题,例如对象键映射,枚举能力(带forEach()
方法)和清除.
function Hashtable() {
this._map = new Map();
this._indexes = new Map();
this._keys = [];
this._values = [];
this.put = function(key, value) {
var newKey = !this.containsKey(key);
this._map.set(key, value);
if (newKey) {
this._indexes.set(key, this.length);
this._keys.push(key);
this._values.push(value);
}
};
this.remove = function(key) {
if (!this.containsKey(key))
return;
this._map.delete(key);
var index = this._indexes.get(key);
this._indexes.delete(key);
this._keys.splice(index, 1);
this._values.splice(index, 1);
};
this.indexOfKey = function(key) {
return this._indexes.get(key);
};
this.indexOfValue = function(value) {
return this._values.indexOf(value) != -1;
};
this.get = function(key) {
return this._map.get(key);
};
this.entryAt = function(index) {
var item = {};
Object.defineProperty(item, "key", {
value: this.keys[index],
writable: false
});
Object.defineProperty(item, "value", {
value: this.values[index],
writable: false
});
return item;
};
this.clear = function() {
var length = this.length;
for (var i = 0; i < length; i++) {
var key = this.keys[i];
this._map.delete(key);
this._indexes.delete(key);
}
this._keys.splice(0, length);
};
this.containsKey = function(key) {
return this._map.has(key);
};
this.containsValue = function(value) {
return this._values.indexOf(value) != -1;
};
this.forEach = function(iterator) {
for (var i = 0; i < this.length; i++)
iterator(this.keys[i], this.values[i], i);
};
Object.defineProperty(this, "length", {
get: function() {
return this._keys.length;
}
});
Object.defineProperty(this, "keys", {
get: function() {
return this._keys;
}
});
Object.defineProperty(this, "values", {
get: function() {
return this._values;
}
});
Object.defineProperty(this, "entries", {
get: function() {
var entries = new Array(this.length);
for (var i = 0; i < entries.length; i++)
entries[i] = this.entryAt(i);
return entries;
}
});
}
Run Code Online (Sandbox Code Playgroud)
Hashtable
get(key)
返回与指定键关联的值.
参数::
key
从中检索值的键.
put(key, value)
将指定的值与指定的键关联.
参数::
key
关联值的键.
value
:要与键关联的值.
remove(key)
删除指定的键及其值.
参数::
key
要删除的键.
clear()
清除所有哈希表,删除键和值.
indexOfKey(key)
根据添加顺序返回指定键的索引.
参数::
key
获取索引的关键字.
indexOfValue(value)
根据添加顺序返回指定值的索引.
参数::
value
获取索引的值.
注意:
此信息是通过indexOf()
数组的方法检索的,因此它只是将toString()
方法与对象进行比较.
entryAt(index)
返回具有两个属性的对象:key和value,表示指定索引处的条目.
参数::
index
要获取的条目的索引.
containsKey(key)
返回哈希表是否包含指定的键.
参数::
key
要检查的键.
containsValue(value)
返回哈希表是否包含指定的值.
参数::
value
要检查的值.
forEach(iterator)
迭代指定的所有条目iterator
.
参数:
value
::用3个参数的方法key
,value
和index
,其中,index
表示所述条目的索引.
length
(只读)
获取哈希表中条目的计数.
keys
(只读)
获取哈希表中所有键的数组.
values
(只读)
获取哈希表中所有值的数组.
entries
(只读)
获取哈希表中所有条目的数组.它们以与该方法相同的形式表示entryAt()
.
function HashTable() {
this.length = 0;
this.items = new Array();
for (var i = 0; i < arguments.length; i += 2) {
if (typeof (arguments[i + 1]) != 'undefined') {
this.items[arguments[i]] = arguments[i + 1];
this.length++;
}
}
this.removeItem = function (in_key) {
var tmp_previous;
if (typeof (this.items[in_key]) != 'undefined') {
this.length--;
var tmp_previous = this.items[in_key];
delete this.items[in_key];
}
return tmp_previous;
}
this.getItem = function (in_key) {
return this.items[in_key];
}
this.setItem = function (in_key, in_value) {
var tmp_previous;
if (typeof (in_value) != 'undefined') {
if (typeof (this.items[in_key]) == 'undefined') {
this.length++;
} else {
tmp_previous = this.items[in_key];
}
this.items[in_key] = in_value;
}
return tmp_previous;
}
this.hasItem = function (in_key) {
return typeof (this.items[in_key]) != 'undefined';
}
this.clear = function () {
for (var i in this.items) {
delete this.items[i];
}
this.length = 0;
}
}
Run Code Online (Sandbox Code Playgroud)