ES6 reverse array iteration, using for .of, did I miss something in the spec?

In ES6 there is now also for .of to repeat them. we have built-in modules for arrays ; in particular keys , values and entries .

These methods allow you to perform most of the iterations that are usually performed. But what about iterating in the opposite direction? This is also a very common task, and I do not see anything in spec specifically for it? Or maybe I missed it?

Ok Array.prototype.reverse , but I don’t necessarily want to undo a large array in place, and then undo it again when done. I also do not want to use Array.prototype.slice to make a temporary shallow copy and the reverse, which is just for iteration.

So, I looked at 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 + '\n')); } 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> 

Is it true that reverse iteration is intended in ES6, or am I missing something fundamental in the specification?

+7
javascript iterator arrays ecmascript-6 reverse
source share
1 answer

Is it true that reverse iteration is for ES6?

A suggestion was made about the reverse iteration, discussed on esdicuss and the git project with a description of spec , but nothing like this happened. ES6 is now complete, so this time it will not be added. Anyway, for arrays and strings, I wrote a little code to fill in the blanks (in my opinion), and I will post it here, as this may help others. This code is based on my browsers today, and some improvements can be made if more ES6 has been implemented on them. I can get around a project or a small github project later.

Update: I created a GitHub project to work on this.

+6
source share

All Articles