无论传入什么字符串,If语句都始终为true

If statement is always true no matter what string I pass in

本文关键字:语句 true If 什么 字符串      更新时间:2023-09-26

我只是在学习javascript。我正在尝试创建一个简单的小费计算器,根据用户对服务质量的描述来更改小费金额。

我为参数、服务传递了一个字符串,并希望检查它是否等于每个小费金额的任何值。如果是这样的话,我会尝试根据这个值来计算小费。

然而,在测试了多个值之后,对于任何值,我的函数在第一个if语句中似乎都是true。我没看到什么?

/* Create an array of possible descriptions of service*/
function tip (cost, service) {
  if (service == "good" || "" || "nice"){
    return cost + cost * .10;
  }else if (service == "bad" || "horrible"){
    return cost + cost * .5;
  }else if (service == "excellent" || "great"){
    return cost + cost * .15;
  }else{
    console.log("How was the service?");
  }
}
console.log(tip(65, "great"));

"或"||的存在是为了方便您,因为它阻止您编写额外的if语句。如果没有||,您的第一条语句将被写成

if (service == "good") 
    return cost + cost * .10;
if ("")
    return cost + cost * .10;
if ("nice")
    return cost + cost * .10;

当它写成这样的时候,你可以看到它不是你的意思。

if("")将始终为false,而if("nice")将始终为true,因此您的其他条件永远不会得到满足。

每次编写条件语句时,都需要在||之间编写每个语句,就好像它是一个单独的if语句一样。在这种情况下,您省略了变量的名称,因此不使用

if (service == "good" || "" || "nice"){

你应该有

if (service == "good" || service == "" || service == "nice"){

另一件需要注意的事情是,在Javascript中,使用===几乎总是比使用==更好。这是因为==在尝试比较值之前会做一些叫做类型强制的时髦事情,但===会直接比较这两个值。

所以你最后的陈述应该是

if (service === "good" || service === "" || service === "nice"){

将同样的意识形态应用于其他所有声明,你就会得到:

function tip (cost, service) {
  if (service === "good" || service === "" || service === "nice"){
    return cost + cost * .10;
  }else if (service === "bad" || service === "horrible"){
    return cost + cost * .5;
  }else if (service === "excellent" || service === "great"){
    return cost + cost * .15;
  }else{
    console.log("How was the service?");
  }
}

这是因为您有|| '' || 'nice',并且此语句将始终为true。你需要这样重写你的声明:

if (service == "good" || service == "" || service == "nice")

你必须对你的所有声明都这样做:

function tip (cost, service) {
  if (service == "good" || "" || "nice"){
    return cost + cost * .10;
  }else if (service == "bad" || service == "horrible"){
    return cost + cost * .5;
  }else if (service == "excellent" || service == "great"){
    return cost + cost * .15;
  }else{
    console.log("How was the service?");
  }
}
console.log(tip(65, "great"));

您的or条件写错了。

service=="good" || "" || "nice"` 

本质上是指

service=="good" || false || true, 

这将始终返回true。

将其更改为低于

function tip (cost, service) {
  if (service == "good" || service == "" || service == "nice"){
    return cost + cost * .10;
  }else if (service == "bad" || service == "horrible"){
    return cost + cost * .5;
  }else if (service == "excellent" || service == "great"){
    return cost + cost * .15;
  }else{
    console.log("How was the service?");
  }
}
console.log(tip(65, "great"));