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?
javascript iterator arrays ecmascript-6 reverse
Xotic750
source share