简体   繁体   English

有人可以向我解释这个 JavaScript 开关代码吗?

[英]Can someone explain this JavaScript switch code to me?

I don't really understand the switch here, from what I know the switch function is supposed allow me to write certain cases and each case is supposed to redirect me to a function, this is an example from my college slides, are the cases numbered "1234","12345", "123" or are those the passwords the user might enter?我不太了解这里的switch ,据我所知, switch函数应该允许我编写某些案例,并且每个case都应该将我重定向到一个函数,这是我大学幻灯片中的一个例子,案例是否编号“1234”、“12345”、“123”还是用户可能输入的密码?

function login() {
    var username = document.myForm.userName.value;
    var password = document.myForm.pass.value;
    if ((username.length == 0) || (password.length == 0)) {
        window.alert("Empty user name or password!");
    } else {
        switch (password) {
            case "12345":
                window.location = "page1.html";
                break;
            case "1234":
                window.location = "page2.html";
                break;
            case "123":
                window.location = "page3.html";
                break;
            default:
                window.alert("Invalid Password");
                document.myForm.pass.select();
        } // end switch case
    }

As you suggested, those are passwords the user might enter.正如您所建议的,这些是用户可能输入的密码。

If the user enters “12345”, the switch statement will enter that case, setting window.location to page1.html.如果用户输入“12345”,switch 语句将进入这种情况,将window.location设置为 page1.html。

“1234” results in window.location being set to to page2.html, and so on. “1234”导致window.location被设置为 page2.html,依此类推。

Note that, if the user enters any value not specified in the switch cases (“12345”, “1234, “123”), the “default” case will be activated, executing window.alert(“Invalid Password”);请注意,如果用户输入任何未在 switch case ("12345", "1234, "123") 中指定的值,“default” case 将被激活,执行window.alert(“Invalid Password”); as well as document.myForm.pass.select();以及document.myForm.pass.select();

The switch (password) means that the variable 'password' is being checked in the current switch case. switch (password)表示在当前开关案例中正在检查变量'password'

So - in case that the password equals what's in the case - the lines of code in that case's scope will be executed until they reach the break .所以-如果要使密码等于什么的case -的代码在这种情况下的范围内线路将被执行,直到他们达到了break

for example :例如 :

var x = 'lala'
switch(x){
  case 'lala':
    foo()
    break;
  case 'lolo':
    bar()
    break;
}

so foo() is going to be executed.所以 foo() 将被执行。

Hope this helped!希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM