简体   繁体   中英

Why do cases in switch statements in JavaScript not have their own code blocks?

Within JavaScript, I was recently experimenting with switch statements to accomplish some parameter checking in a for-in loop and I found that the syntax does not feel like it is very consistent with the theme of using code blocks in JavaScript.

My example data is the following:

var data = {
    one: "hello",
    two: "world"
}

What I would imagine a switch statement to look like would be:

function isDataRoughlyMyExample(data) {
    if (typeof data !== "object") {
        return false;
    }
    let count = 0;
    for (const name in data) {
        count++;
        switch (name) {
            case "one", "two" {
                if (typeof data[name] !== "string") {
                    return false;
                }
            }
            default {
                return false;
            }
        }
    }
    if (count === 0) {
        return false;
    } else {
        return true;
    }
}

However JavaScript seems to follow the general theme of python by having the code block use the white space for code readability

function isDataRoughlyMyExample(data) {
    if (typeof data !== "object") {
        return false;
    }
    let count = 0;
    for (const name in data) {
        count++;
        stuff: switch (name) {
            case "one":
            case "two":
                if (typeof data[name] !== "string") {
                    return false;
                }
                break stuff;
            default:
                return false;
        }
    }
    if (count === 0) {
        return false;
    } else {
        return true;
    }
}

To clarify, I am asking why switch statements work the way they do. I am aware that it is unlikely to be changed due to JavaScript's love for backwards compatibility, but it does confuse me why it is like this.

That's also how switch works/looks in several other languages (most noteworthy of them being C). So, adding these code blocks would increase confusion, not decrease it.

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