0

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」に置き換えると、undefinedで「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;
};
4

1 に答える 1

1

This is what I would do:

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

Then you create your array as follows:

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

You're doing inheritance in JavaScript wrong. Read about it here.

You can see the demo here: http://jsfiddle.net/dWKTX/1/

于 2012-12-05T16:04:12.147 に答える