Discord.js v13 中,使用 Collection 类来存储键值对。在进入到集合时,可以使用 Collection.prototype.get() 方法来获取特定项的值,或使用 Collection.prototype.forEach() 方法来遍历所有的项。
例如,假设有一个名为 myCollection 的集合,其中包含了 {key: 'value'} 和 {key: 'value2'} 两个项。
获取特定项的值:
const { Collection } = require("discord.js");
const myCollection = new Collection();
myCollection.set('item1', { key: 'value' });
myCollection.set('item2', { key: 'value2' });
const item1Value = myCollection.get('item1');
console.log(item1Value); // 输出 {key: 'value'}
遍历所有的项:
const { Collection } = require("discord.js");
const myCollection = new Collection();
myCollection.set('item1', { key: 'value' });
myCollection.set('item2', { key: 'value2' });
myCollection.forEach((value, key) => {
console.log(`Item ${key}'s value is: ${value}`);
});
// 输出:
// Item item1's value is: [object Object]
// Item item2's value is: [object Object]
注意:在使用 forEach() 方法时,参数的顺序必须是 (value, key) 而不是 (key, value)。
参考文献:Discord.js Collection class