我正在学习JS。所以我正在尝试创建一个函数,但“其他”部分不起作用。你能帮我理解原因吗?
function accesSite() {
let ageLimite = prompt("How old are you ?");
if (ageLimite >= 16) {
var yes = " Ok, you can drive ! ";
} else {
var no = "No, you can't drive!";
}
let message = "Can you drive ?" + yes || no;
return message
}
alert(accesSite());
答案 0 :(得分:7)
您可以执行以下操作。声明一个变量,然后相应地更改它:
function accesSite(){
let ageLimite = prompt("How old are you ?") >= 16;
//create variable
var canDrive = "";
if (ageLimite >= 16){
//change it accordingly
canDrive = " Ok, you can drive ! " ;
} else {
//change it accordingly
canDrive = "No, you can't drive!" ;
}
let message = "Can you drive ? " + canDrive ;
return message
}
alert(accesSite());

一行中更好的版本:
function accesSite(){
return "Can you drive ? " + ( prompt("How old are you ?") >= 16 ? " Ok, you can drive ! " : "No, you can't drive!");
}
alert(accesSite());

答案 1 :(得分:4)
您可以对logical OR ||
使用括号,因为加号具有更高的operator precedence作为逻辑OR。
let message = "Can you drive? " + (yes || no);
// ^^^^^^^^^^^ evaluate first
更好的方法是在顶部声明所有常量和变量,并直接返回结果,而不为返回字符串提取另一个变量。
该功能具有提前退出范例,这意味着如果您需要从函数返回,您可以按照不需要else
部分的方式组织条件,因为你使用return
在早期阶段终止了这个功能。
来源:
function accesSite(){
const canYouDrive = "Can you drive? ";
var ageLimite = prompt("How old are you?");
if (ageLimite >= 16){
return canYouDrive + "Ok, you can drive!";
}
return canYouDrive + "No, you can't drive!" ;
}
alert(accesSite());

答案 2 :(得分:2)
在我们修复它的同时,我们可以使代码更清晰:
function accesSite(){
let ageLimite = prompt("How old are you ?");
let message = "Can you drive ? ";
if (ageLimite >= 16)
return message + " Ok, you can drive !";
return message + "No, you can't drive!" ;
}
alert(accesSite());
请注意,我在此处删除了else
块:
true
,则您点击return statement
。 return
以下的任何内容都无法执行。 false
,则不会执行第一个块,将不会调用if
的{{1}},因此return
下面的代码而是执行{1}}。或者使用ternary condition:
if
我个人更喜欢将function accesSite(){
let ageLimite = prompt("How old are you ?");
return "Can you drive ? " + (ageLimite >= 16 ? " Ok, you can drive!" : "No, you can't drive!");
}
alert(accesSite());
结果保存在变量中。 Imo,更具可读性。
答案 3 :(得分:1)
function accesSite() {
let ageLimite = prompt("How old are you ?");
var msg = "Can you drive ? ";
if (ageLimite >= 16) {
msg = msg + " Ok, you can drive ! ";
} else {
msg = msg + "No, you can't drive!";
}
let message = msg;
return message
}
alert(accesSite());