Javascript 尝试使用特定字符串和布尔值解决If/else问题
问题 我尝试过多种途径并观看了视频。我被卡住了Javascript 尝试使用特定字符串和布尔值解决If/else问题,javascript,if-statement,Javascript,If Statement,问题 我尝试过多种途径并观看了视频。我被卡住了 function exerciseThree(typeOfPizza){ let lovesPizza; // In this exercise, you will be given a variable, it will be called: typeOfPizza // You are also given another variable called: lovesPizza; // Using an if/else stat
function exerciseThree(typeOfPizza){
let lovesPizza;
// In this exercise, you will be given a variable, it will be called: typeOfPizza
// You are also given another variable called: lovesPizza;
// Using an if/else statement assign lovesPizza to true if typeOfPizza is 'pepperoni', assign it to false if it is 'olives'
我所尝试的:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
又一次尝试
// if(lovesPizza===pepperoni){
// return true
//}
//else (lovesPizza===olives){
// return false
// }
另一个
//if (lovesPizza.equals(pepperoni))
// return "true";
//else (lovesPizza.equals(olives))
// return "false"
正如评论所说,你正在寻找。你也应该仔细检查你对问题的理解,你的检查/分配变量的方式是错误的
函数练习三(Pizza类型){
让爱斯皮扎;
if(Pizza的类型=='pepperoni'){
lovesPizza=正确;
}else if(typeOfPizza==='olives'){
lovesPizza=假;
}
log('lovesPizza:',lovesPizza);
};
练习三(“辣香肠”);
练习三个(“橄榄”);
我当然希望你们老师是在捉弄你们。
没有明智的建议,如果你把“火腿”之类的东西放进去,怎么办,而且不处理,所有的可能性都是草率的
let lovesPizza;
function exerciseThree(typeOfPizza){
if(typeOfPizza === 'pepperoni') {
return true;
} else if (typeOfPizza === 'olives') {
return false;
} else {
return undefined;
}
}
lovesPizza = exerciseThree('pepperoni');
console.log(lovesPizza); // true
lovesPizza = exerciseThree('olives');
console.log(lovesPizza); // false
lovesPizza = exerciseThree('ham');
console.log(lovesPizza); // undefined
我强烈建议在这里使用switch语句。在我看来,Switch语句运行得更快,更容易使用 但要指出你做错了什么: 在这里你要检查lovesPizza是否有意大利香肠的价值。但你们应该检查一下比萨的类型。这就是为什么您很可能没有定义:
if (lovesPizza==='pepperoni') {
// The value is empty.
return true;
}
else {
(lovesPizza==='olives')
return false;
}
用switch语句检查一下它的外观
函数练习三(Pizza类型){
开关(PIZZA型){
“辣香肠”一案:
返回true;
“橄榄”案:
返回false;
违约:
返回false;
}
}
练习三(“辣香肠”);
练习三个(“橄榄”);
您的else语句需要if
if(somethingisTrue)
{
return "it is true";
}
else if(somethingelseistrue)
{
return "no the other thing was true";
}
else
{
return "nothing is true"
}
另外===检查字符串是否相等,是否都是字符串。通常最好确保if的情况是不必要的
if(!typeOfPizza)
{
//raise an error as null was passed in
return "false"
}
else if(typeOfPizza.toLowerCase().trim()==="pepperoni"){
{
return true..... you can build the rest
我经常编写一个名为cleanString或compareString的函数(原型),以执行所有正常的字符串清理
一个简单的解决方案是,但不按要求使用ifs
function exerciseThree(typeOfPizza){
let lovesPizza= typeOfPizza==="pepperoni";
return lovesPizza;
}
如果你想在
else
之后有一个不同的条件,那么你需要另一个if
,所以你要做if(condition1){}else if(condition2){}
同样,你应该比较typeoppizza
,而不是lovesPizza
。注意下面的措辞:“如果typeoppizza是‘pearoni’,就把lovesPizza赋值给true”。您检查了错误的变量。您还返回了,而不是将lovesPizza
赋值给true/false
,感谢georg指出这一点。这就成功了。愚蠢的打字错误!