1

I need an kind of "circular array". I have everything working but for single instance. I don't know how to make it "instantiable". I mean I want it to work the following way:

var arr = ['a', 'b', 'c', 'd']; // it's kind of pseudo-code 
arr.getNext(); // gives a
arr.getNext(); // gives b
arr.getNext(); // gives c
arr.getNext(); // gives d
arr.getNext(); // gives a
arr.getNext(); // gives b
// and so on

I know I can create object with array inside and iterate over it, but I'm pretty sure I can do this the other way.

The problem is I need several instances of that object. If it was only one instance I could do:

var arr = ['a', 'b', 'c', 'd'];
arr.getNext = function() {
  // ... I got this stuff working
}

How to allow createion of several instances of such custom arrays?

4

3 回答 3

4

即使您可以扩展(Array.prototypeObject.defineProperty创建不可枚举的属性),替代解决方案也可能很有趣,具体取决于您的实际需求。

您可以定义一个在数组上返回迭代器的函数:

function iter(arr) {
    var index = -1;

    return {
        next: function() {
            index = (index + 1) % arr.length;
            return arr[index];
        }
    };
}

用法:

var it = iter(arr);
it.next();
于 2013-07-04T10:55:27.407 回答
1

您可以扩展prototype以便能够在以下所有实例中使用它Array

Array.prototype.getNext = function(){
  var next = this.shift();
  this.push(next);
  return next;
};

请注意,这会修改数组。

于 2013-07-04T10:52:53.077 回答
0

您可以将 getNext 方法添加到 Array 原型中,如下所示:

Array.prototype.getNext = function ()
{
....
}

然后,您可以在您创建的任何数组上调用此方法。

于 2013-07-04T10:52:10.343 回答