2012-12-05 35 views
0

我想有一個基於Uint32Array的數組。數組的長度應該隨着元素數量的增長而遞增。同時我想要「length」屬性返回元素的數量,而不是底層數組的大小。例如:如何覆蓋保留訪問權限的Uint32Array.length屬性?

var a = new myArray(); 
a.length; // returns 0, the size of underlying array is 10 
a.add(0); 
a.length; // returns 1, the size of underlying array is 10 
... 
a.add(9); 
a.length; // returns 10, the size of underlying array is 10 
a.add(10); 
a.length; // returns 11, the size of underlying array is 20 

下面的代碼顯示了我是如何實現它的。唯一的障礙是訪問原始數組的「length」屬性。代碼中的「父」字僅用於示例。如果我將它替換爲「this.prototype」,它會在未定義中顯示「this.prototype.length」。

是否可以解決它?

var myArray = function() { 
this._length = 0; 
return this; 

// defining the getter for "length" property 
Object.defineProperty(this, "length", { 
    get: function() { 
     return this._length; 
    }, 
}; 

myArray.prototype = new Uint32Array(myArray.increment); 
myArray.increment = 10; 
myArray.add = function(val) { 
    if (this.length <= parent.length) { 
     _a = new Uint32Array(parent.length + myArray.increment); 
     _a.set(this); 
     this = _a; 
    }; 
    this[this.length++] = val; 
}; 

回答

1

這是我會做:

function MyArray(increment) { 
    var array = new Uint32Array(increment); 
    var length = 0; 

    Object.defineProperty(this, "length", { 
     get: function() { 
      return length; 
     } 
    }); 

    this.add = function (value) { 
     if (length === array.length) { 
      var ext = new Uint32Array(length + increment); 
      ext.set(array); 
      array = ext; 
     } 

     var index = length++; 
     array[index] = value; 

     Object.defineProperty(this, index, { 
      get: function() { 
       return array[index]; 
      }, 
      set: function (value) { 
       array[index] = value; 
      } 
     }); 
    }; 
} 

然後,創建數組如下:

var a = new MyArray(10); 
a.length; // returns 0, the size of underlying array is 10 
a.add(0); 
a.length; // returns 1, the size of underlying array is 10 
... 
a.add(9); 
a.length; // returns 10, the size of underlying array is 10 
a.add(10); 
a.length; // returns 11, the size of underlying array is 20 

你在JavaScript中做錯了繼承。閱讀有關它here

你可以在這裏看到演示:http://jsfiddle.net/dWKTX/1/

+0

謝謝你的答覆。我做了你的建議。但是,然後你放棄了像這樣的數組訪問:a [i]。 – Dmitry

+0

讓我糾正這一點。 –

+0

好吧,我糾正了這個問題,併爲你添加了一個小小的演示。 –