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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…