你的對象類和數組鍵混合。
function Obj() {} //create Obj object
var a = new Obj(); //a is instance Obj object
var b = new Obj(); //b is instance Obj object
var hash = {}; //create hash object
hash[a] = 1; //its not create key array in hash object - hash{[{a}]:1}
hash[b] = 2; // hash{[{b}]:2}
//hash = {[Object Object]:2}
console.log(hash[a]); //its return last assign value - 2
console.log(hash[b]); //2
對象分配密鑰無效
簡單的事情是
function Obj() {}
var a = new Obj();
var b = new Obj();
a={"name":"David"};
b={"name":"Naest"};
var hash = {};
hash[0] = a;
console.log(hash[0].name); //David
hash[1] = b;
console.log(hash[1].name); //Naest
如果u要覆蓋對象鍵作爲另一個對象鍵
function Hash(){
var hash = new Object();
this.put = function(key, value){
if(typeof key === "string"){
hash[key] = value;
}
else{
if(key._hashtableUniqueId == undefined){
key._hashtableUniqueId = UniqueId.prototype.genarateId();
}
hash[key._hashtableUniqueId] = value;
}
};
this.get = function(key){
if(typeof key === "string"){
return hash[key];
}
if(key._hashtableUniqueId == undefined){
return undefined;
}
return hash[key._hashtableUniqueId];
};
}
function UniqueId(){
}
UniqueId.prototype._id = 0;
UniqueId.prototype.genarateId = function(){
return (++UniqueId.prototype._id).toString();
};
使用
function Obj() {}
var a = new Obj();
var b = new Obj();
var hash = new Hash();
hash.put(a,1);
hash.put(b,2);
console.log(hash.get(a)); //1
如果你想使用對象作爲鍵,可以考慮使用ES6地圖。 –