How to simulate JavaScript yield?

前端 未结 5 1820
误落风尘
误落风尘 2020-12-28 19:03

One of the new mechanisms available in JavaScript 1.7 is yield, useful for generators and iterators.

This is currently supported in Mozilla browsers only (that I\'m

5条回答
  •  天涯浪人
    2020-12-28 19:40

    Similar to Pointy's answer, but with a hasNext method:

    MyList.prototype.iterator = function() { //MyList is the class you want to add an iterator to
    
        var index=0;
        var thisRef = this;
    
        return {
            hasNext: function() {
                return index < thisRef._internalList.length;
            },
    
            next: function() {
                return thisRef._internalList[index++];
            }
        };
    };
    

    The hasNext method let's you loop like:

    var iter = myList.iterator() //myList is a populated instance of MyList
    while (iter.hasNext())
    {
        var current = iter.next();
        //do something with current
    }
    

提交回复
热议问题