简体   繁体   中英

Javascript Switch: can you use the same case multiple times?

I have a switch based on an elements "type" that triggers different default settings.

Multiple "types" often share default settings like backgroundColor so we bunch them together in a multiple case setup. As we modify it's nice to be able to adjust each "type" as we go and often end up with a lot of duplication as then it's each type in it's own little box.

What I'd like to do is use a case where it is shared, and then again later declare it for its special properties.

Something like:

function setDefaults(base) {
    switch (base.type) {
            case 'rectangle':
            case 'circle':
            case 'areaMap':
            case 'clock':
            case 'news':
            case 'weather':
            case 'webview':
            case 'camera':
                base.properties.background = this._getRandColor();

            case 'areaMap':
                base.properties.height = '600px';
                base.properties.width = '800px';
                break;
        }
    return base;
}

I'm not sure if this will work or not...

No, it doesn't work. It only seems to work because you are missing a break after the first case. Without that break , if the second case was called anything, it would be executed.

For instance, if you called the second case case 'foo': it would still set height/width properties. The height and width are applied because of the missing break in the previous case statement.

Credit @machinegost and @jorg for the following additional sources, respectively:

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