在 javascript 中向字典添加新键(它只是重置它)discord.js

Adding new keys to dictionary in javascript (Its just resetting it) discord.js

好的,所以我有一个名为 create 的命令,我想将键和值添加到名为 plans

的字典中

所以命令是这样的:!create plan.(plan name) (plan)

这是我的代码:

if (args[1].startsWith('plan.')) { //This checks if the user wants to create a plan
    name = args[1].replace('plan.', '') //This variable is the same as args[1] but plan. is cut off
    plans[name] = args[2] //This is the code i am having touble with but i want it to add a new key and value to plans
    message.channel.send('Added plan for **' + name + '**') //Message from the bot saying that the plan was added
    console.log(args) //All the print statements that i used to find out the problem
    console.log(plans)
    console.log(name)
}

好的,所以 plans[name] = args[2] 是我遇到的问题,因为当我写(给机器人)时会发生什么

!create plan.Mod PlanForMod 这是 console.log 版画的输出:

[ 'create', 'plan.Mod', 'PlanForMod' ] { Mod: 'PlanForMod' } Mod

第一个是 args 变量,第二个是 plans 字典,第三个是 name var

这很完美吧?但是如果我想添加另一个计划,这是我的输出(我输入 !create plan.Admin Adminplan

[ 'create', 'plan.Admin', 'Adminplan' ] { Admin: 'Adminplan' } Admin

如您所见,它没有添加另一个键,而是用新的键和值替换了整个字典

我有另一个命令可以打印用户想要的计划

命令:!plan (plan name)

代码:

let myValue = plans[args[2]]
            message.channel.send(myValue)
            console.log(plans)

如果我输入上面显示的内容,然后输入:!plan Mod 它说我不能发送空消息,即使我输入:!create plan.Mod Mod 然后输入 !plan Mod 它仍然说同样的事情,因为当我用 console.log() 命令打印出字典时,我得到了这个:

{} (node:8456) UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message at RequestHandler.execute (C:\Users\Bruker\Desktop\BCN\node_modules\discord.js\src\rest\RequestHandler.js:170:25) at processTicksAndRejections (internal/process/task_queues.js:97:5) (node:8456) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag--unhandled-rejections=strict(see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3) (node:8456) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

注意到空括号了吗?它只是把它铺好!

我该如何解决这个问题?

总和: 我希望命令添加另一个键,但它用新键替换了整个字典。如果我在整个字典为空后尝试打印它

第一个问题可能是作用域

我假设您有一些与此类似的代码

client.on("message", msg => {
  const plans = {};
});

client.on("message", msg => {
  //...code
  if(args[0] === "plan") {
    const plans = {};
  }
});

无论使用哪种代码,您每次都在创建一个新对象,而是:

const plans = {};
client.on("message", msg => {
   //code
});

现在这是全球范围,但这是一个不同的问题

第二个代码的问题是您使用的是索引 2 而不是 1。

因为来自 !plan Mod 的参数将是 ["!plan", "Mod"] 或类似的东西

另一个问题是范围界定,因为它是一个空对象,我假设您的代码与我发送的第一个代码块相似。应该通过修复解决。