JavaScript哈希表/字典
考虑下面这篇用JavaScript解释哈希表/字典的文章: 根据公认的答案,我希望能够做到这一点:JavaScript哈希表/字典,javascript,ecmascript-5,jscript,Javascript,Ecmascript 5,Jscript,考虑下面这篇用JavaScript解释哈希表/字典的文章: 根据公认的答案,我希望能够做到这一点: var instance = new Dictionary(); instance['key1'] = 'Foo'; instance['key2'] = 'Bar'; instance['key3'] = 123; instance['key4'] = true; 但是我希望键/值对在内部指向字典中的对象。考虑下面的代码结构 var Dictionary = function() {
var instance = new Dictionary();
instance['key1'] = 'Foo';
instance['key2'] = 'Bar';
instance['key3'] = 123;
instance['key4'] = true;
但是我希望键/值对在内部指向字典中的对象。考虑下面的代码结构
var Dictionary = function() {
var dictionary; // <-- key value pairs should point to this, not to the Dictionary function;
this.setValue = function(key, value) {
dictionary[key] = value;
}
this.getValue = function() {
return dictionary[key];
}
}
这方面的问题是:
上述两种情况都不应该发生,因此set和get功能应该应用于内部对象,而不是字典本身。为什么?为什么不干脆
var实例={}
?@JonHanna,因为字典将是“强”(如果可以与JS一起使用)类型库的一部分,其中字典将表示与Java或C#类似的结构。将实例定义为{}会破坏库结构,因为{}也可以应用于任何其他对象类型。既然所有的对象都能做到这一点,也许只需要创建一个与您的类型匹配的类型(如果有的话),就可以了?@JonHanna,还有一点。第一个方面是“填充”任何未定义的“本机”js对象。然后,对象将被分配额外的功能,并使用继承模型形成层次结构。最后,像Dictionary这样的对象也将添加到层次结构中。虽然我知道它是一个普通对象,但它必须继承其祖先的功能(并在必要时重写),并添加其他功能。希望这是有意义的:-我想是的,但是你仍然在添加它已经拥有的功能,这就是我不明白的地方。所有javascript对象都继承了成为字典的功能,那么您实际添加的是什么呢//显示“undefined”(遗憾的是缺乏语法便利性,我们必须通过getValue)…它正在实现……但它仍然需要这个功能。我可能不得不玩保护功能不被覆盖的游戏!这要求您重载[]
操作符,这在javascript中是无法做到的。看啊,这回答了我的问题!非常感谢。
function Dictionary()
{
this.store = {};
this.setValue = function(key, value) {
store[key] = value;
}
this.getValue = function(key)
{
return store[key];
}
return this;
}
//Testing
var dict = Dictionary();
dict.setValue('key','value');
alert(dict.getValue('key'));//displays "value"
alert(dict.getValue('unassignedKey'));//displays "undefined"
alert(dict['key']);//displays "undefined" (an unfortunate lack of syntactic convenience, we have to go through getValue).
alert(dict.key);//displays "undefined"
var dict2 = Dictionary();
dict2.setValue('key2', 'value2');
alert(dict2.getValue('key'));//displays "undefined"
alert(dict2.getValue('key2'));//displays "value2"
function Dictionary()
{
this.store = {};
this.setValue = function(key, value) {
store[key] = value;
}
this.getValue = function(key)
{
return store[key];
}
return this;
}
//Testing
var dict = Dictionary();
dict.setValue('key','value');
alert(dict.getValue('key'));//displays "value"
alert(dict.getValue('unassignedKey'));//displays "undefined"
alert(dict['key']);//displays "undefined" (an unfortunate lack of syntactic convenience, we have to go through getValue).
alert(dict.key);//displays "undefined"
var dict2 = Dictionary();
dict2.setValue('key2', 'value2');
alert(dict2.getValue('key'));//displays "undefined"
alert(dict2.getValue('key2'));//displays "value2"