2

I'm trying out the new Set object in node 4.1.2 and I'm seeing that the values, keys, and entries methods all always return empty objects. For example:

var x = new Set
x.add(1)
x.add(2)
x.values() // returns {}

Is this expected behavior? I can't imagine it is.

B T
  • 57,525
  • 34
  • 189
  • 207
  • Isn't `x.values()` an iterator? What happens if you `.next().value` it? – zero298 Oct 06 '15 at 19:16
  • Heyyy, `x.values().next().value` seems to work. That leads to the question: why does javascript have iterators? And since it has iterators, why don't they work in `for(x in y)` loops? – B T Oct 06 '15 at 19:51
  • Because you use `for ( let z of x ) {console.log(z);}` now – zero298 Oct 06 '15 at 20:00
  • Ah I see. Its not actually that "you use ..`of`.. now" - the use of `for..in` hasn't changed at all. Rather, `for..of` is a new construction that iterates over values rather than keys, and since iterators have no keys, `in` doesn't have anything to loop through. I still think they would have done well to stay away from the concept of iterators. – B T Oct 06 '15 at 20:30

2 Answers2

1

ES6 has added some new tricks including iteration protocols. You may want to take a look at Iteration Protocols on MDN to get a tighter grasp on how to utilize them. for(item in array) is still around, but you can use the new for ... of on certain things.

Considering your code:

var x = new Set
x.add(1)
x.add(2)
x.values()

Let us say that, where var y = x.values();, y is an iterator;

In order to iterate over said iterator, you use a for(let item of iterable){} loop. In this instance, you would be using:

for(let z of x){
    console.log(z);
}

Which would print out:

1
2
zero298
  • 25,467
  • 10
  • 75
  • 100
  • Looks like converting iterators to arrays isn't quite there in 2.5.0, but is there in v4: http://stackoverflow.com/questions/27612713/convert-es6-iterable-to-array – B T Oct 06 '15 at 22:52
0

The values are there, it's just that util.inspect() was not showing them. This was fixed already in master with 88533881d, which was post-v4.1.2. So you will see the fix whenever v4.1.3 gets released.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • `for(var n in x.values()) {console.log(n)}` logs nothing, so I don't think its just a `util.inspect()` problem. – B T Oct 06 '15 at 19:51