首页 > 解决方案 > 这个 if 语句究竟做了什么?

问题描述

我正在Discord Bot使用discord.jsV12 开发,我的代码中有一些我不明白的行。

我的命令处理程序:

const fs = require('fs');

module.exports = (client, Discord) => {
    const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
    
    for(const file of command_files) {
        const command = require(`../commands/${file}`);
        
     //This is the if statement I dont understand   
      if(command.name)
        {
        client.commands.set(command.name, command); // and also this line thx.
        } else
        {
            continue;
        }
   }
};

有人可以向我解释这些吗?谢谢。

标签: node.jsdiscord.js

解决方案


首先if statement

if(command.name) 

检查 的属性是否namecommands

  • 如果为空,则**不执行括号内的代码,直接跳转到else block
  • 如果没有,它将执行括号内的代码

第二行

client.commands.set(command.name, command);

调用该.set()函数以将具有这些参数的新命令添加到commands集合中:

  • command.name显然command要添加的名称
  • command具有所有属性和可执行功能的对象本身

推荐阅读