2011-08-08 92 views
1

有没有一种方法可以制作一个关联数组,其中每个键都是多个对象的散列?我不想检查每个对象的状态,而是检查对象的身份。使用多个对象作为键的散列/关联数组

var myarray = {}; 

var a = new A(); 
var b = new B(); 
var c = new C(); 

// + is not right, but illustrates the hashing I'm after. 
myarray[a + b + c] = 42; 

+运算符是不正确的。在Java中,我会算术结合这三个实例中的每一个的System.identityHashCode(),并使用结果来创建我的新哈希键。在JavaScript中有一些类似的机制吗?

覆盖A,B和C中的.toString()方法不是一个选项,因为我对对象标识感兴趣,而不是状态。

+0

实际上是不可能的,因为这种语言中的“对象键”只能是字符串。 – jAndy

+0

好的答案jAndy。将其张贴为一个,我可以接受它;) –

回答

3

实际上是不可能的,因为在这种语言对象键只能是字符串,而且也没有Java的对象身份的等价物。

:o)

+0

我虚心接受我的numptieness。 –

+0

@MartinAlgesten:其实你的编辑也是不必要的。简单的语句“对象键”可能只是字符串很清楚。对象关键字不能是'数字',不能是'boolean',不能是'object',它可以只是一个'string'。 – jAndy

+0

我认为这是相关的。如果javascript有一个对象身份的概念,比如为每个创建的对象计数一个'number',我总是可以用它来创建我后面的唯一ID字符串。 –

2

您可以覆盖原型的toString()方法以为每个实例创建唯一的散列。例如。

A.prototype.toString = function() { 
    return /* something instance specific here */; 
}; 

即使a + b + c会工作。

更新: Afaik,你不能在JavaScript中得到一个实例唯一的id(不管是什么)。但是,您可以为每个实例分配一些标识符

这只适用于正在创建的对象。

E.g.

var addIdentityTracker = (function() { 
    var pad = "0000000000", 
     id = 1; 

    function generateId() { 
     var i = (id++).toString(); 
     return pad.substr(0, 10 - i.length) + i; 
    } 

    return function(Constr) { 
     var new_constr = function() { 
      this.___uid = generateId(); 
      Constr.apply(this, arguments); 
     }; 
     new_constr.prototype = Constr.prototype; 

     new_constr.prototype.toString = function() { 
      return this.___uid; 
     }; 

     return new_constr; 
    }; 
}()); 

然后执行:

A = addIdentityTracker(A); 
var a = new A(); 
+0

这正是我试图避免谈论“不感兴趣检查每个对象状态”的答案。我需要身份,而不是状态。 –

+0

@Martin:你可以给每个实例一个id ...我不认为你在这里有任何其他的可能性。 –

+0

我认为jAndy正在接近真相。一个键总是一个字符串,所以对象标识的概念是不适用的... –

1

我建议只给每个对象分配一个唯一的ID。 Javascript没有内置的唯一ID机制,但是你可以为你想要的任何对象分配一个唯一的ID,然后像这样使用它。例如,你可以这样做:

// getUniqueID is a function that returns a unique ID for any javascript object. 
// If no uniqueID is already present on the object, it coins one using a global 
// counter and then stores it on the object. 
// So that the uniqueID can be combined with other uniqueIDs easily and still 
// create a unique union, the uniqueID here is a unique 10 character string. 
// There is no randomness in the IDs as they are only required to be unique 
// within the page, not random or unique in the universe. The monotomically 
// increasing counter guarantees uniqueness within the page. 

// Two globals we need for generating the unique ID  
var idCntr = 0; 
var controlStr = "0000000000"; // 10 digits long 

function getUniqueID(o) { 
    if (!o.uniqueID) { 
     var base = idCntr++ + ""; // get string version of idCntr 
     o.uniqueID = controlStr.slice(0, controlStr.length - base.length) + base; // zero pad 
    } 
    return(o.uniqueID); 
} 

var myobj = {}; 

var a = new A(); 
var b = new B(); 
var c = new C(); 

myobj[getUniqueID(a) + getUniqueID(b) + getUniqueID(c)] = 42; 

为您获取相同的对象回来以后,你不得不对象按正确的顺序重新组合。如果这不容易,那么您可以确保并始终按照数字顺序将它们与最低的数字结合起来,这样您始终可以获得一致的顺序。