【问题标题】:Variables outside of an if statement in discord.js [closed]discord.js中if语句之外的变量[关闭]
【发布时间】:2021-06-16 17:06:17
【问题描述】:

我需要使用某些变量只有在触发时才具有值,但我需要在if 语句之外使用这些变量。有谁知道怎么做?

代码:

      let commandRan = false
      let User = msg.author.id
      if (msg.content.toLowerCase().startsWith("pe!command")){
        msg.channel.send('Hello! say 1 or 2');
        commandRan = true
        User = msg.author.id
      };
      
        if (msg.content.toLowerCase().startsWith("1")){
                  if (commandRan === true) {
                    if (User === msg.author.id){ 
                      msg.channel.send("1!")
                    }
                  }
              } else if (msg.content.toLowerCase().startsWith("2")){         
                    msg.channel.send("2!")
              }

【问题讨论】:

    标签: javascript scope discord.js


    【解决方案1】:

    在 if 方法外声明变量并影响其内部的值:

    let v1; //this is the var declaration.
    //your code
    
    if(<some condition>){
      v1 = "something";
    }
    //more code
    if (v1 !== undefined){
      console.log(v1);
    //whatever you want to do in this case    
    }
    

    注意 undefined 是保留关键字

    更多信息可以在这里找到in the mozilla fondation docs

    【讨论】:

      猜你喜欢
      • 2012-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 1970-01-01
      • 2012-10-20
      相关资源
      最近更新 更多