简体   繁体   English

JavaScript集-向集合内对象中的数组添加值

[英]javascript sets - adding value to array in object inside a set

I'm trying to make an array of sets to make something like this 我正在尝试制作一组​​数组来制作这样的东西

{
    'user1': ["value#1", "value#2",..."value#N"],
    'user2': ["value#2",..."value#N"],
    'userN': [..."value#N"]
}

and then remove the value#x after 5 seconds (for example). 然后在5秒钟后删除value#x #x(例如)。

here is my code: 这是我的代码:

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);

instead of getting output like the first code, i get this output instead 而不是像第一个代码那样得到输出,我得到了这个输出

Set { 'command1', 'command2',
'USER1': 'command3',
'USER2': 'command4'
'USERN': 'commandN'
}

Feel free to comment if you have a question, so sorry if my question is hard to understand 如有问题,请随时发表评论,如果我的问题难以理解,请抱歉

A Set for this purpose is not necessary but I did a small POC that could help you to implement the solution you need: 为此,不需要Set,但是我做了一个小的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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM