为什么使用Object作为键的Javascript哈希覆盖另一个Object键?

时间:2015-09-17 04:20:56

标签: javascript

function Obj() {}
var a = new Obj();
var b = new Obj();
var hash = {};
hash[a] = 1;
hash[b] = 2;
console.log(hash[a]); // 2
console.log(hash[b]); // 2
console.log(a == b); // false

我以为hash会使用a和b的指针地址作为键,这不是真的吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
  

如果你想要将对象密钥覆盖为另一个对象密钥

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