本文介绍了如何在javascript中以相反的顺序迭代Set或Map?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种迭代或或也是从开始到开始。
The iterator given from Set.prototype.values() or Set.prototype.entries() are also from start to beginning.
以相反的顺序迭代Set(或Map)的解决方案是什么?
What would be the solution to iterate the Set (or Map) in the reverse order?
推荐答案
没有办法在地图或集合上获得反向迭代器,正如我在尝试。所以唯一的方法就是使用中间数组并将其反转,如下所示:
There is no way to obtain a reversed iterator on Maps or Sets, as I have found out while trying to get the last item added to a Set. So the only way really is to use an intermediate Array and reverse it, like this:
var mySet = new Set([1,2,3,4,5]);
for (let myNum of Array.from(mySet).reverse()) {
console.log(myNum);
}
或者您可以使用此备用双向链接Set实现:
Or you can use this alternate doubly linked Set implementation:
class LinkedSetLink {
constructor(value) {
this.value = value;
this.prev = this;
this.next = this;
}
insertBefore(item) {
const prev = item.prev = this.prev;
const next = item.next = this;
next.prev = item;
prev.next = item;
}
remove() {
const prev = this.prev;
const next = this.next;
next.prev = prev;
prev.next = next;
}
}
class LinkedSet {
constructor(iterable) {
this._map = new Map();
this._pivot = new LinkedSetLink(/* undefined */);
if (iterable) {
this._addAll(iterable);
}
}
_addAll(iterable) {
for (const item of iterable) {
this.add(item);
}
}
has(item) {
return this._map.has(item);
}
add(item) {
if (!this._map.has(item)) {
const link = new LinkedSetLink(item);
this._pivot.insertBefore(link);
this._map.set(item, link);
}
}
delete(item) {
const link = this._map.get(item);
if (link) {
this._map.delete(item);
link.remove();
}
}
clear() {
this._map.clear();
this._pivot.next = this._pivot.prev = this._pivot;
}
get size() {
return this._map.size;
}
values() {
return this._map.keys();
}
keys() {
return this.values();
}
[Symbol.iterator]() {
return this.values();
}
*entries() {
for (const key of this.values()) {
yield [key, key];
}
}
*reversedItems() {
let link = this._pivot.prev;
while (link !== this._pivot) {
yield link.value;
link = link.prev;
}
}
first() {
return this._pivot.next.value;
}
last() {
return this._pivot.prev.value;
}
}
const myset = new LinkedSet([1,2,3,4,5]);
for (let item of myset.reversedItems()) {
console.log(item);
}
这篇关于如何在javascript中以相反的顺序迭代Set或Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!