简体   繁体   English

Switch语句不适用于某些变量

[英]Switch statement doesn't work with some variables

I want to make the Angular2 Pipe which returns different values according to passed variable. 我想使Angular2 Pipe根据传递的变量返回不同的值。 The variable device.display can be of different type (object or string) and takes only two values null and "dataTime" . 变量device.display可以具有不同的类型(对象或字符串),并且仅接受两个值null"dataTime"

Component part: 组成部分:

<div class="col col-2">{{values[variable.id] | display: device.display}}</div>

Pipe: 管:

Pipe
import { Pipe } from '@angular/core';
@Pipe({
    name: 'display'
})
export class DisplayPipe {
    transform(value: any, display: string): string {
        display = String(display);
        switch (display) {
            case 'dateTime': {
                value = value * 60;
            }
            case 'null': {
                value = value;
           }
        default: value = 'abc';
        }
    return value;
    }
}

I'm sure that after parsing variable to String it is equal to "null" or "dateTime" . 我确定在将变量解析为String之后,它等于"null""dateTime" I checked it with console.log . 我用console.log检查了它。

The problem is the switch statement always returns default value: "abc" . 问题是switch语句始终返回默认值: "abc"

Wrong Syntax. 语法错误。 You don't need brackets in each case, and you forgot the break; 在每种情况下都不需要括号,并且您忘了break; statement. 声明。

Heres an example, on how you build switch case: 以下是有关如何构建开关盒的示例:

switch (new Date().getDay()) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case 6:
        day = "Saturday";
}

That's not correct sintaxis for switch: 那不是切换的正确方法:

switch (display) {
            case 'dateTime':
                value = value * 60;
                break;
            case 'null':
                value = value;
                break;
            default: 
               value = 'abc';
        }

if you dont break on every case, switch will execute all cases, then how you are setting same variable on all cases, the value is the last case default: abc. 如果您不中断所有情况,则switch将执行所有情况,然后在所有情况下如何设置相同的变量,该值为最后一个情况默认值:abc。

如果您错过了Java中的break语句, 则会发生穿透情况,因此执行默认语句,并且值始终为“ abc”

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

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