我正在使用 Near-sdk-as 的 PersistentMap 存储键值,现在我想遍历所有键和值,这可能吗?
PS:near-docs中给出的PersistentMap接口只包含get、set等基本方法。
我正在使用 Near-sdk-as 的 PersistentMap 存储键值,现在我想遍历所有键和值,这可能吗?
PS:near-docs中给出的PersistentMap接口只包含get、set等基本方法。
目前这是不可能的。您必须将密钥存储在单独的数组中,可能使用PersistentVector
. 然后,您可以遍历 中的键PersitentVector
,并从 中获取值PersistentMap
。
这是一个关于如何做到这一点的(不完整的)示例。
@nearBindgen
export class Contract {
keys: PersistentVector<string> = new PersistentVector<string>('keys');
myMap: PersistentMap<string, string> = new PersistentMap<string, string>(
'myMap'
);
constructor() {}
// Custom function to keep track of keys, and set the value in the map
mySet(key: string, value: string): void {
// don't add duplicate values
if (!this.myMap.contains(key)) {
this.keys.push(key);
}
this.myMap.set(key, value);
}
// Get values from map, iterating over all the keys
getAllValues(): string[] {
const res: string[] = [];
for (let i = 0; i < this.keys.length; i++) {
res.push(this.myMap.getSome(this.keys[i]));
}
return res;
}
// Remember to remove the key from the vector when we remove keys from our map
myDelete(){
// TODO implement
}
}
PersistentMap 的实现中还有一个注释
(1) Map 不存储键,因此如果您需要检索它们,请在值中包含键。
以下是 的可用功能PersistentMap
。APersistentMap
基本上是使用现有存储的辅助集合。你给PersistentMap
一个唯一的前缀,当你使用set(key)
Map 时,将创建另一个唯一的键,将前缀与传递给的键结合起来set(key)
。这只是使用现有存储的一种便捷方式。