我正在尝试制作一组集合来制作类似的东西
{
'user1': ["value#1", "value#2",..."value#N"],
'user2': ["value#2",..."value#N"],
'userN': [..."value#N"]
}
然后在 5 秒后删除 value#x
(例如)。
这是我的代码:
var myset = new Set();
var ran = myset[USERID] = commandNumber;
//i'm trying to make "if myset contains userNumber AND commandName" return,
//if its not, run someFunction() and continue
if (myset.has(ran)) return;
someFunction();
myset.add(ran);
setTimeout(() => {
myset.delete(ran);
}, 5000);
我得到的不是像第一个代码那样的输出,而是这个输出
Set { 'command1', 'command2',
'USER1': 'command3',
'USER2': 'command4'
'USERN': 'commandN'
}
如果您有任何问题,请随时发表评论,如果我的问题难以理解,很抱歉
最佳答案
不需要为此目的设置一套,但我做了一个小型 POC,可以帮助您实现所需的解决方案:
'use strict';
const mySet = new Set();
const mySetMetadata = {};
const removeFromSet = (userKey, commandName) => {
const commands = mySetMetadata[userKey] || [];
if (commands.includes(commandName)) {
mySetMetadata[userKey] = commands.filter(c => c !== commandName);
if (mySetMetadata[userKey].length === 0) {
mySet.delete(userKey);
mySetMetadata[userKey] = undefined;
}
}
};
/**
* Add relation between an userKey and a command
* @param {String} userKey
* @param {Array} commands Array of commands
*/
const addToSet = (userkey, commands) => {
mySet.add(userkey);
if (typeof mySetMetadata[userkey] === 'undefined') {
mySetMetadata[userkey] = commands;
} else {
mySetMetadata[userKey] = [...mySetMetadata[userKey], ...commands]
}
}
// Populate with demo data
addToSet('user1', ['value#1', 'value#2', 'value#N']);
addToSet('user2', ['value#2', 'value#N']);
addToSet('user3', ['value#N']);
// Set up a timeout for a given user + key
setTimeout(() => {
removeFromSet('user1', 'value#2');
}, 5000);
关于javascript set - 将值添加到集合内对象的数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50776255/