【问题标题】:javascript sets - adding value to array in object inside a setjavascript 集合 - 向集合内对象中的数组添加值
【发布时间】:2018-11-19 10:28:28
【问题描述】:

我正在尝试制作一组​​集合来制作这样的东西

{
    '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'
}

如果您有任何问题,请随时发表评论,如果我的问题难以理解,请见谅

【问题讨论】:

  • myset[USERID] 真的吗?它向集合实例添加了一个新属性,但集合的任何特性都不能用于它。
  • 点击<>并生成minimal reproducible example
  • 好吧,@mplungjan,要删除这个并发布一个新的。或编辑这个
  • 为什么不创建一个sn-p?你的代码可以显示它做了什么

标签: javascript arrays node.js object discord.js


【解决方案1】:

不需要为此目的的 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);

【讨论】:

  • 我,以某种方式解决了这个问题,但这个看起来和我的很相似,甚至更干净。非常感谢!会试试这个:)
猜你喜欢
  • 2015-12-18
  • 1970-01-01
  • 1970-01-01
  • 2014-07-29
  • 2019-06-13
  • 2012-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多