ES6 reverse iterate an array using for..of, have I missed something in the spec?

后端 未结 2 1434
伪装坚强ぢ
伪装坚强ぢ 2020-12-10 03:53

In ES6 we now have iterators and for..of to iterate them. we have some built-ins for arrays; notably keys, values and entries.

These methods allow one to perform muc

相关标签:
2条回答
  • 2020-12-10 04:33

    Is this really the way that reverse iteration is intended in ES6?

    There was a proposal for reverse iteration, discussed on esdicuss and a git project outlining a spec, but nothing much seemed to happen with respect to it. ES6 is finalised now, so it's not something that is going to be added this time around. Anyway, for arrays and strings I've written a little code to fill in the gaps (in my opinion) and I will post it here as it may help others. This code is based on my browsers today and some improvements could possibly be made if there was more of ES6 implemented on them. I may get around to a gist or a small github project later.

    Update: I have created a GitHub project for work on this.

    0 讨论(0)
  • 2020-12-10 04:41

    Have a look at https://www.npmjs.com/package/itiriri.
    It's a library that has similar methods as arrays, but works with iterators.

    import { query } from 'itiriri';
    
    const m = new Map();
    m.set(1, 'a');
    m.set(2, 'b');
    m.set(3, 'c');
    
    const result = query(m);
    
    for (const [k, v] of result.reverse()) {
      console.log(k + ' - ' + v)
    }
    

    query returns an iterable that has similar methods as arrays. In above example reverse() is used. There are also fitler, slice, map, concat etc.

    If you need back an array, or a map from a query you can use one of .toArray(), .toMap() or .toSet() methods.

    0 讨论(0)
提交回复
热议问题