2012-02-21 128 views
1

如何在JavaScript中使用字典的功能?如何通過JavaScript中的鍵使用對象來獲取值?

看這個question指定的方式工作,但我設置的功能實例作爲這樣一個關鍵:

Scale = function() 
{ 
    this.Collections = {}; 
    this.IndexTracker = {}; 
    this.UpdateIndex = function() 
    { 
     var index = 0; 
     for (var i = 0; i < this.Collections.length; i++) 
     { 
      this.SetIndex(this.Collections[i], index++); 
     } 
    } 
    this.SetIndex = function (obj, value) 
    { 
     this.IndexTracker[obj] = value; 
    } 
    this.GetIndex = function (obj, value) 
    { 
     return this.IndexTracker[obj]; 
    } 
} 

this.Collections將舉辦一些函數實例。

這裏的問題是函數實例被this.Collections中的下一個函數實例覆蓋。 Collections的長度始終爲1。如何解決這個問題?

enter image description here

+0

這可能是一個範圍問題 - 使用'var'關鍵字,因此變量('this.Collections'等)僅範圍內的存在的函數(對象),而不是保存到全局範圍中。 – 2012-02-21 10:30:50

+1

鍵將被視爲字符串。如果你使用與鍵不同的數據類型,它將被轉換爲字符串。默認的字符串表示形式是'[object Object]',因此您可以考慮使用另一個鍵作爲鍵(例如,使用您自己的對象序列化)。 – 2012-02-21 10:30:58

+0

[Hash /關聯數組使用多個對象作爲關鍵字]的可能重複(http://stackoverflow.com/questions/6983436/hash-associative-array-using-several-objects-as-key) – 2012-02-21 10:33:39

回答

1

這是一個例子:

var Scale = function() { 
    var _Collections = {}, 
    _IndexTracker = {}, 
    ret = function() { 
     function UpdateIndex() { 
      var index = 0,i,l; 
      for (i = 0,l=_Collections.length; i < l; i++) { 
       this.SetIndex(_Collections[i], index++); 
      } 
     } 
     function SetIndex(obj, value) { 
      _IndexTracker[obj] = value; 
     } 
     function GetIndex(obj, value) { 
      return _IndexTracker[obj]; 
     } 
     return { 
      UpdateIndex : UpdateIndex, 
      SetIndex : SetIndex, 
      GetIndex : GetIndex 
     }; 
    }; 
    return ret; 
}(); 
相關問題