JavaScript Iterators

后端 未结 6 1510
清酒与你
清酒与你 2020-12-28 23:03

I was going through MDN (Mozilla Developer Network) and came across Iterators and generators

So naturally, I tried the snippets of code given in the page on Google C

6条回答
  •  无人及你
    2020-12-28 23:33

    var makeIterator = function (collection, property) {
        var agg = (function (collection) {
        var index = 0;
        var length = collection.length;
    
        return {
          next: function () {
            var element;
              if (!this.hasNext()) {
                return null;
              }
              element = collection[index][property];
              index = index + 1;
              return element;
            },
          hasNext: function () {
            return index < length;
          },
          rewind: function () {
            index = 0;
          },
          current: function () {
            return collection[index];
          }
        };
     })(collection);
    
     return agg;
    };
    
    
    var iterator = makeIterator([5,8,4,2]);
    
    console.log(iterator.current())//5
    console.log(  iterator.next() )
    console.log(iterator.current()) //8
    console.log(iterator.rewind());
    console.log(iterator.current()) //5
    

提交回复
热议问题