无论我传入什么字符串,if语句总是为真

时间:2015-11-27 01:10:13

标签: javascript string

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

我为参数service发送一个字符串,并想检查它是否等于每个提示量的任何值。如果是这样,我会尝试根据该值计算提示。

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

/* 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"));

3 个答案:

答案 0 :(得分:5)

“or”||存在是为了您的方便,因为它会阻止您编写额外的if语句。如果没有||,您的第一个语句将被写为

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

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

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

每次编写条件语句时,都需要在||之间编写每个语句,就好像它是一个单独的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?");
  }
}

答案 1 :(得分:4)

这是因为你有|| '' || 'nice',这句话一直都是真的。你需要像这样重写你的陈述:

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"));

答案 2 :(得分:2)

您或您的条件写错了。

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"));