Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
272 views
in Technique[技术] by (71.8m points)

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

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 much of the iteration one would commonly perform. But, what about iteration in reverse? This is also a very common task and I don't see anything in the spec specifically for it? Or maybe I missed it?

Ok, we have Array.prototype.reverse but I don't necessarily want to reverse a large array in place and then reverse it again when finished. I also don't want to use Array.prototype.slice to make a temporary shallow copy and reverse that just for iteration.

So I took a look a generators and came up with these working solutions.

(function() {
  'use strict';

  function* reverseKeys(arr) {
    let key = arr.length - 1;

    while (key >= 0) {
      yield key;
      key -= 1;
    }
  }

  function* reverseValues(arr) {
    for (let key of reverseKeys(arr)) {
      yield arr[key];
    }
  }

  function* reverseEntries(arr) {
    for (let key of reverseKeys(arr)) {
      yield [key, arr[key]];
    }
  }

  var pre = document.getElementById('out');

  function log(result) {
    pre.appendChild(document.createTextNode(result + '
'));
  }

  var a = ['a', 'b', 'c'];

  for (var x of reverseKeys(a)) {
    log(x);
  }

  log('');
  for (var x of reverseValues(a)) {
    log(x);
  }

  log('');
  for (var x of reverseEntries(a)) {
    log(x);
  }
}());
<pre id="out"></pre>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...