代码之家  ›  专栏  ›  技术社区  ›  random

javascript对象数组

  •  0
  • random  · 技术社区  · 16 年前

    我需要将Java中的代码迁移到JavaScript。 在爪哇中,我用对象的key =字符串和value=ARAYLIST来维护一个哈希图。

    我需要在javascript中实现同样的功能:

    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);
    

    但是当我试图获取指定键的属性时

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

    我得到值=id2,这是为hashmapdataset对象设置的最后一个id。

    我尝试在javascript中模拟getter和setter,如下链接所示: 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关联起来。请帮助。

    3 回复  |  直到 16 年前
        1
  •  1
  •   user187291    16 年前

    我不太清楚你想在那里做什么,但是在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;
    
        2
  •  0
  •   ATorras    16 年前

    javascript闭包循环问题非常常见。

    我会花很多时间: http://www.javascriptkata.com/2007/04/11/a-common-problem-with-the-powerful-javascript-closures/

    当做。

        3
  •  0
  •   xdevel2000    16 年前

    对于不需要私有函数的类,可以直接使用特权函数:

        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;
           }
       }