简体   繁体   中英

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?

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.

“1234” results in window.location being set to to page2.html, and so on.

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”); as well as document.myForm.pass.select();

The switch (password) means that the variable 'password' is being checked in the current switch case.

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 .

for example :

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

so foo() is going to be executed.

Hope this helped!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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