0

我想要一个基于 Uint32Array 的数组。数组的长度应该随着元素数量的增加而增加。同时我希望“长度”属性返回元素的数量,而不是底层数组的大小。例如:

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

1 回答 1

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 中的继承是错误的。在这里阅读。

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

于 2012-12-05T16:04:12.147 回答