如何在js中将对象放在HashMap中?

时间:2013-12-25 11:46:04

标签: javascript

我这样创建简单HashMap,但当我将object作为value放入此地图时,我无法调用object's function地图,我发现objectstring函数转换为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]

3 个答案:

答案 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();

小提琴链接:http://jsfiddle.net/hCH8k/

答案 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'),这对我来说是正确的......: - )