Trying to understand iterables please a little help here

Hi

I'm trying to understand the concept of Iterables, so I have popped into W3schools and follow this little guide. https://www.w3schools.com/js/js_object_iterables.asp

In which I can clearly understand that

A protocol has been set in which it states that:
    - An object becomes an iterator when it implements a next() method.
    - The next() method must return an object with two properties
        - value (the next value)
        - done (true or false)

So I am trying to cook a homemade iterable by doing my own object

var myObject = {
    bandName : "Rage Against",
    albumName : "Evil Empire",
    next() {
        var outputObject = {
            value : 3,
            done : true
        }
        return outputObject;
    }
};

for( var i of myObject ) {
    console.log(i);
}

This give me a

TypeError: myObject is not iterable

And adapting it a bit to the guide's object I finnally write

var myObject = {
    bandName : "Rage Against",
    albumName : "Evil Empire",
    next() {
        var n;
        n++
        var outputObject = {
            value : n,
            done : false
        }
        return outputObject;
    }
};

for( var i of myObject ) {
    console.log(i);
}

Which gives me the same error

The issue is that in the guide he declares a function instead of an object

// Home Made Iterable
function myNumbers() {
  let n = 0;
  return {
    next: function() {
      n += 10;
      return {value:n, done:false};
    }
  };
}

// Create Iterable
const n = myNumbers();
n.next(); // Returns 10
n.next(); // Returns 20
n.next(); // Returns 30

And I am trying to stick to the strict definition of it. Anyone can pave me the way? Thank you

Posted May 4, 2022, 1:42 AM UTC

312
Loading comments…