【问题标题】:confusion with weather command, how do i fix it?与天气命令混淆,我该如何解决?
【发布时间】:2021-05-06 22:49:39
【问题描述】:

我正在制作一个,weather 命令,我希望它适用于摄氏度和华氏度,但我希望我的命令检测最后一个参数,例如 ,weather toronto 会给我多伦多摄氏的天气,当我做,weather toronto f 时,它给了我华氏度的天气,但是当我做类似,weather new york city f``` 之类的事情时,它没有给我华氏度的天气,这是该部分的代码,天气部分是由 weather-js npm 完成

        if(args[1] == "C" || args[1] == "c"){
            var Degree = "Celsius"
            var Deg = "C"
        }
        else if(args[1] == "F" || args[1] == "f"){
            var Degree = "Fahrenheit"
            var Deg = "F"
        }
        else{
            var Degree = "Celsius"
            var Deg = "C"
        }

【问题讨论】:

标签: javascript discord discord.js


【解决方案1】:

args 是一个给定命令的参数数组,在大多数命令处理程序中以空格分隔。与其像其他编码人员建议的那样使用某个字符在城市名称的单词之间分割,不如让它变得不那么用户友好,如果您严格要求选择位于最后一个索引处,您可以使用:array[array.length - 1].

let degree;
let deg;
if (args[args.length - 1].toLowerCase() === 'f') {
  degree = 'Fahrenheit';
  deg = 'F';
} else { // Keep in mind, checking if the last index is 'c' is not necessary, as we'll set it to celsius anyways.
  degree = 'Celsius';
  deg = 'C';
}

【讨论】:

    【解决方案2】:

    假设您使用的是Arguments,weather new york city f 不起作用的原因是因为您的命令行被空格分割,并且格式为[cmd] [location] [degree type]

    这将使new位置,york学位类型。这当然是无效的。


    使用空格来说明位置名称的一种方法是将输入除以破折号-new-york-city 而不是new york city)然后使用@ 重新格式化字符串987654322@和Array#join()

    // message.content = ',weather new-york-city f`
    // const args ...
    
    console.log(args);
    // ['new-york-city', 'f']
    
    args[0] = args[0].split('-').join(' ');
    // ['new-york-city'] => 'new york city'
    

    如果您喜欢保留位置中的空间,可以使用此

    // const args ...
    const Location = args.slice(0, args.length - 1);
    
    // Using Optional chaining (?.) Since a degree argument is optional (node v14+)
    const Deg = args?.pop();
    

    您的最终代码如下所示

    const Location = args.slice(0, args.length - 1);
    const Deg = args?.pop()?.toUpperCase();
    
    let Degree = '';
    if (Deg === 'C' || !Deg) {
       Degree = 'Celsius';
    } else {
       Degree = 'Fahrenheit';
    }
    

    更好的是,使用Ternary Operator 处理所有问题。

    const Location = args.slice(0, args.length - 1);
    const Deg = args?.pop()?.toUpperCase();
    const Degree = Deg === 'C' || !Deg ? 'Celsius' : 'Fahrenheit';
    

    【讨论】:

    • 第二个效率如何?您基本上是在说,只有当城市长度为 3 个字而不是更少,而不是更多时,它才会起作用。
    猜你喜欢
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多