2009-11-20 119 views
0

我需要将Java中的代码迁移到JavaScript。 在java中,我保持与关键=字符串值=对象JavaScript对象数组

我需要实现同在JavaScript的ArrayList的一个HashMap:

this.hashMap = new Hash(); 
this.hashMapArrayList =[]; 
... 
var hashMapDataSet = new HashMapDataSet(id1,name1,type1); 
this.hashMapArrayList[0] = hashMapDataSet; 
... 
this.hashMap.set(fileName1, this.hashMapArrayList); 

var hashMapDataSet1= new HashMapDataSet(id2,name2,type2); 
this.hashMapArrayList[0] = hashMapDataSet1; 
this.hashMap.set(fileName2, this.hashMapArrayList); 

但是,当我试图让该属性指定key

this.hashMap.get(fileName1).getId() 

我得到value = id2,它是为HashMapDataSet对象设置的最后一个id。

我试图模仿getter和setter在javascript如下面的链接中指定: http://javascript.crockford.com/private.html

这里是HashMapDataSet类

function HashMapDataSet(pId, pName, pType) { 
var id = pId; 
var name = pName; 
var type = pType; 

function getId1() { 
return id; 
} 
function setId1(mId) { 
id = mId; 
} 
.... 

this.getId = function() { 
return getId1(); 
}; 

this.setId = function (id) { 
setId1(id); 
}; 

... 
} 

其中getId1,setId1是私有方法和 的getId, setId是特权方法

我是JavaScript新手,所以我无法将java对象与javascript关联起来。请帮助。

回答

1

我不太清楚你想在那里做什么,但在JavaScript中,你不需要所有的java接线,因为该语言具有内置的地图和列表。你的代码片段可以在js中看起来像这样:

this.hashMap = {}; 
this.hashMapArrayList =[]; 
... 
this.hashMapArrayList.push({id: id1, name: name1, type: type1}); 
... 
this.hashMap.fileName1 = this.hashMapArrayList; 

this.hashMapArrayList.push({id: id2, name: name2, type: type2 }); 
this.hashMap.fileName2 = this.hashMapArrayList; 
+0

一个目标是不是很安全的,因为在一般情况下,地图中使用。你只能有String键,并且使用与'toString'等Object属性冲突的某些键会导致浏览器问题加剧。 – bobince 2009-11-20 13:41:27

0

为类,你不需要专用的功能,你可以直接使用特权功能:

function HashMapDataSet(pId, pName, pType) 
    { 
     var id = pId; 
     var name = pName; 
     var type = pType; 

     this.getId = function() 
     { 
      return id; 
     }; 

     this.setId = function (pId) 
     { 
      id = pId; 
     } 
    }