2012-12-05 4 views
0

Uint32Array를 기반으로 배열을 만들고 싶습니다. 배열의 길이는 요소의 양이 증가하는 동안 점진적으로 증가해야합니다. 동시에 "길이"속성을 기본 배열의 크기가 아닌 요소 수를 반환합니다. 예 :원본 속성에 대한 액세스를 유지하는 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 

아래 코드는 구현 방법을 보여줍니다. 유일한 장애물은 원래 배열의 "길이"속성에 대한 액세스입니다. 코드의 "상위"단어는 예제에 불과합니다. "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

이 내가 할 것 인 것이다 : 당신이 잘못 자바 스크립트에서 상속을하고있는

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 

다음과 같이

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

그런 다음 당신이 당신의 배열을 만들 수 있습니다. 약 here에 대해 읽어보십시오.

당신은 여기에서 데모를 볼 수 있습니다

+0

http://jsfiddle.net/dWKTX/1/가 답장을 보내 주셔서 감사합니다. 나는 네가 제안한 것을했다. 그런 다음 배열에 대한 액세스를 느슨하게합니다 : a [i]. – Dmitry

+0

내가 그것을 바로 잡자. –

+0

좋아요, 문제를 해결하고 당신을 위해 약간의 데모를 추가했습니다. –

관련 문제