我这样创建简单HashMap
,但当我将object
作为value
放入此地图时,我无法调用object's function
地图,我发现object
被string
函数转换为toString
。那么我应该怎样做才能将object itself
而不是字符串放入地图?
var g_itemMap =
{
put : function(key,value){this[key] = value},
get : function(key){return this[key]},
contains : function(key){return this.get(key) == null?false:true},
remove : function(key){delete this[key]}
}
我把对象放在这样:
g_itemMap.put(1, object);
得到它:
var object = g_itemMap.get(1);
当我调用它的功能时,它出错了:
object.somefunction();
警告可以显示对象:
[object BitmapItem]
答案 0 :(得分:1)
这段代码看起来像是在为我工作。 你可以试试这个;
var g_itemMap =
{
put : function(key,value){this[key] = value},
get : function(key){return this[key]},
contains : function(key){return this.get(key) == null?false:true},
remove : function(key){delete this[key]}
}
var object =
{
objectfunction: function(){
console.log('objectfunction called')
}
}
g_itemMap.put(1, object);
var o = g_itemMap.get(1);
o.objectfunction();
答案 1 :(得分:1)
var HashMap = new Object();
HashMap[Key1] = Obj1;
HashMap[Key2] = Obj2;
function get(k)
{
console.log(HashMap[k]);
}
或者只是你可以使用
var HashMap = {"Key1":"value1","Key2":"value2"}
function get(k)
{
console.log(HashMap[k]);
}
答案 2 :(得分:0)
如果我尝试
var object = { a: function() { alert('b'); } };
var g_itemMap =
{
put : function(key,value){this[key] = value},
get : function(key){return this[key]},
contains : function(key){return this.get(key) == null?false:true},
remove : function(key){delete this[key]}
}
g_itemMap.put(1, object);
var object2 = g_itemMap.get(1);
object2.a();
警告(' b'),这对我来说是正确的......: - )