我正在学习带有多个条件的if-else语句,这个简单的任务使我感到困扰,因为在Visual Studio代码中强调了外部条件的else。我似乎无法解决它。它说“声明或声明预期”。你们能帮我看看吗?这是我的代码。
TypeTag : ClassTag
答案 0 :(得分:1)
考虑到您使用的是相同的文本-仅包含性别和年龄变量-可以将这些逻辑转换为变量,然后将其插入被控制的短语中。
因为有两个参数传递给该函数并不意味着每个变量都必须位于if / else块之内
function solve(input) {
var gender, ability;
input[0] == 'Female'
? gender = 'lady'
: gender = 'dude';
parseInt(input[1]) >= 18
? ability = 'are'
: ability = 'are not';
console.log('You ' + ability + ' permitted on the website, ' + gender + '.')
}
solve(['Female', '13']); // gives You are not permitted on the website, lady.
solve(['Male', '19']); // give You are permitted on the website, dude.
答案 1 :(得分:0)
正如注释部分已经提到的,您的else if
语句引用了function
块,但是您必须引用第一个if
语句。重新对齐您的代码/大括号,您的代码应按预期工作:
function solve(input) {
let gender = (input.shift());
let age = Number(input.shift());
if (gender === 'Female') {
if (age >= 18) {
console.log('You are permitted on the website, lady.');
} else {
console.log('You are not permitted on the website, lady.');
}
} else if (gender === 'Male') {
if (age >= 18) {
console.log('You are permitted on the website, dude.');
} else {
console.log('You are not permitted on the website, dude.');
}
} else {
console.log('Error');
}
}
solve(['Female', '13']);
仅作为建议,请使用分号关闭控制台日志语句(例如console.log("output");
)。请参阅this帖子,以获取有关用分号结束语句的更多信息。