gpt4 book ai didi

javascript - switch 语句 default 总是显示 default

转载 作者:行者123 更新时间:2023-11-30 07:12:09 30 4
gpt4 key购买 nike

我有一个 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.");
}

为什么会这样?

最佳答案

因为您的 switch case 中没有任何 break

查看 MDN 上的 switch 语句的文档.它说了以下关于 break 的内容(强调我的)

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement.

所以更新你的案例看起来像

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

关于javascript - switch 语句 default 总是显示 default,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56381728/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com