2015-09-17 66 views

回答

0

想通了。 JS哈希使用toString()作爲鍵。例如這個工程:

function Obj() { 
    var str = "" + Math.random(); 
    this.toString = function() { 
    return str; 
    } 
} 
var a = new Obj(); 
var b = new Obj(); 
var hash = {}; 
hash[a] = 1; 
hash[b] = 2; 
console.log(hash[a]); // 1 
console.log(hash[b]); // 2 
console.log(a == b); // false 
+0

是的,你可以通過執行'for(var i in hash)console.log(typeof i);'< - outputs'string' – Jan

+0

你可能會喜歡新的符號JS即將發佈...... – dandavis

0

你的對象類和數組鍵混合。

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 
相關問題