27 November 2010

Array of Arrays (Two Dimensional Arrays) in JavaScript

כאשר רוצים ליצור מערך של מערכים  ב JavaScriptזה בדר"כ נראה קוד מסובך, וקשה לתחזק אותו.
בניתי קוד שדומה לHash או Dictionary שיש לו Key והוא האיבר המצביע על המערך השני שהוא הValue.
פונים אליו בשני דרכים
הראשונה, כל פעם (בדרך כלל בלולאות) מוסיפים למערך ב SetAnItem:
var arr1 = new RoiArray();
arr1.SetAnItem("One",1);
arr1.SetAnItem("Two",1);
arr1.SetAnItem("Three",1);
השנייה, בו זמנית מכניסים את כל המערך:
var arr2 = new RoiArray("One",[1,1,1],"Two", "two", "Three",3);


למערך יש אפשרות להסיר מהרשימה (RemoveAnItem) על פי הKey, לבדוק שקיים Key מסוים (HasItem) וכמובן לקבל את הערך (GetAnItem) של המפתח.

הקוד של הJS:
function RoiArray()
{
  this.length = 0;
  this.items = new Array();
  for (var i = 0; i < arguments.length; i += 2) {
    if (typeof(arguments[i + 1]) != 'undefined') {
      this.items[arguments[i]] = arguments[i + 1];
      this.length++;     
    }
  }
  
  this.RemoveAnItem = function(in_key) 

  
      
    var tmp_value; 
    if (typeof(this.items[in_key]) != 'undefined') {
      this.length--;
      var tmp_value = this.items[in_key];
      delete this.items[in_key];
    }     
    return tmp_value; 

  
   
  this.GetAnItem =
function(in_key) {
    return this.items[in_key]; 
  }
  this.SetAnItem = function(in_key, in_value) {
    if (typeof(in_value) != 'undefined') {
      if (typeof(this.items[in_key]) == 'undefined') {
        this.length++;
      }
      this.items[in_key] = in_value;    
    } 
     
    return in_value; 

  
  
  this.HasItem = function(in_key) 
        
    return typeof(this.items[in_key]) != 'undefined'

  }
}
נחמד, לא?
שבוע טוב,
רועי

No comments:

Post a Comment