switch语句default总是显示default

时间:2019-05-30 16:01:41

标签: javascript

我有一个switch语句。它几乎可以正常工作,但是它不仅显示一个案例,还显示所选案例,然后显示默认案例。这是我的代码:

var people = {
  names: ["Sam", "Tim", "Steve"],
  emails: ["sam@email.com", "timm@messages.org", "stevieG@youhavemail.com"],
  phonenums: [1111, 2222, 4545]
}

var search = prompt("Type in someone's name to find their phone number and email.");

switch (search) {
  case people.names[0]:
    alert(people.names[0] + "'s email: " + people.emails[0] + " phone number: " + people.phonenums[0]);
  case people.names[1]:
    alert(people.names[1] + "'s email: " + people.emails[1] + " phone number: " + people.phonenums[1]);
  case people.names[2]:
    alert(people.names[2] + "'s email: " + people.emails[2] + " phone number: " + people.phonenums[2]);
  default:
    alert("I don't know that person.");
}

为什么会这样?

3 个答案:

答案 0 :(得分:5)

因为您的切换箱中没有break

MDN上查看switch语句的文档。它说了关于break强调我的

的以下内容
  

与每个案例标签关联的可选break语句确保一旦执行匹配的语句,程序就退出switch 并在切换后的语句处继续执行。如果省略break,程序将在switch语句的下一个语句处继续执行。

因此将您的案件更新为类似

case people.names[0]:
  alert(people.names[0] + "'s email: " + people.emails[0] + " phone number: " + people.phonenums[0]);
  break;

答案 1 :(得分:2)

您需要提供一个break语句

答案 2 :(得分:2)

如果您不希望运行默认值,则需要在switch语句中插入中断。只需这样做:

var people = {
    names : ["Sam", "Tim", "Steve"],
    emails : ["sam@email.com", "timm@messages.org", "stevieG@youhavemail.com"],
    phonenums : [1111, 2222, 4545]
}

var search = prompt("Type in someone's name to find their phone number and email.");
switch(search) {
    case people.names[0]:
        alert(people.names[0] + "'s email: " + people.emails[0] + " phone number: " + people.phonenums[0]);
        break;

    case people.names[1]:
        alert(people.names[1] + "'s email: " + people.emails[1] + " phone number: " + people.phonenums[1]);
        break;

    case people.names[2]:
        alert(people.names[2] + "'s email: " + people.emails[2] + " phone number: " + people.phonenums[2]);
        break;

    default:
        alert("I don't know that person.");
}

在您的特定情况下,最好搜索并使用正确的人的索引,这样您的数组就可以自由地增长和收缩。这样的事情可能会起作用:

var search = prompt("Type in someone's name to find their phone number and email.");
boolean found = false;
int i = 0;
while(!found && i<people.names.length) {
    if(people.names[0] == search){
        found=true;
    } else {
        i++;
    }
}
if(found){
        alert(people.names[i] + "'s email: " + people.emails[i] + " phone number: " + people.phonenums[i]);
} else {
        alert("I don't know that person.");
}

我的js生锈了,我正在用手机,如果没有其他人发现,我将稍后检查语法错误。