我正在做一个,weather
命令,我希望它工作在摄氏,华氏温度,但我希望我的命令能探测到最后一个参数,例如,,weather toronto
会给我多伦多的天气以摄氏单位表示,当我做,weather toronto f
时,它会给我以fahrenhiet表示的天气,但是当我做类似于天气的事情时,它不会给我以华氏度表示的天气,这里是这个部分的代码,天气部分是由天气完成的-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"
}
发布于 2021-05-06 14:13:32
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';
}
发布于 2021-05-06 14:10:41
假设您使用的是参数,那么,weather new york city f
不能工作的原因是您的命令行是按空格拆分的,并且具有[cmd] [location] [degree type]
格式。
这将使new
成为位置,而york
将成为度类型。当然是无效的。
一种用空格解释位置名称的方法是,让输入用破折号-
(new-york-city
而不是new york city
)来划分,然后使用String#split()和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';
}
更好的是,用一个三元算子来处理这一切。
const Location = args.slice(0, args.length - 1);
const Deg = args?.pop()?.toUpperCase();
const Degree = Deg === 'C' || !Deg ? 'Celsius' : 'Fahrenheit';
https://stackoverflow.com/questions/67419712
复制相似问题