본문 바로가기

개발하자

논리적 및 논리적으로 스크립트 스위치 대/소문자 입력

반응형

논리적 및 논리적으로 스크립트 스위치 대/소문자 입력

스위치 명세서를 작성하려고 하는데 제가 원하는 대로 작동하지 않는 것 같아요.

getExerciseDescription(exerciseId, intensity_level){

    alert(exerciseId + " " + intensity_level)

    switch (exerciseId && intensity_level) {
        case (1 && 1):
        this.header="Exercise 1 Level 1";
        this.instructions="Exercise 1 Level 1";
        break;
        case (1 && 2):
        this.header="Exercise 1 Level 2";
        this.instructions="Exercise 1 Level 2";
        break;  


        case (2 && 1):
        this.header="Exercise 2 Level 1";
        this.instructions="Exercise 2 Level 1";
        break;  
        case (2 && 2):
        this.header="Exercise 2 Level 2";
        this.instructions="Exercise 2 Level 2";
        break;

        default:
        this.header="Default";
        this.instructions="Default";
        break;
    }

    return new Popup(this.header, this.instructions);
} 

알림은 2와 1을 제공하지만 반환되는 값은 (1 & 1)에 대한 값입니다. 그것은 왜 그럴까? 어떻게 고칠 수 있죠?




논리 연산자 및 항상 반환되는 정도의 가능한 스위치 사례는 참이고 거짓입니다. 문자열이나 숫자 케이스만 사용해야 합니다.




그것은 성명서가 평가하는 방식이 아니다. 시나리오의 경우 항상 논리적 및 에서 두 번째 정수로 평가됩니다.

(자세한 내용은 )

논리 AND(&&)

expr1 && expr2

false로 변환할 수 있으면 expr1을 반환하고, 그렇지 않으면 expr2를 반환합니다. 따라서 부울 값과 함께 사용할 경우 &&는 두 피연산자가 모두 참이면 true를 반환하고, 그렇지 않으면 false를 반환합니다.

당신은 사실 스위치를 사용할 필요도 없고, 간단한 것으로 작성할 수 있다.

if (exerciseId <= 2 && intensity_level <= 2){
    this.header=`Exercise ${exerciseId} Level ${intensity_level}`;
    this.instructions=`Exercise ${exerciseId} Level ${intensity_level}`;
} else {
    this.header="Default";
    this.instructions="Default";
}



그런 식으로 a를 사용할 수는 없습니다. 그리고, 당신은 다음과 같은 일을 하고 있습니다.

    switch (exerciseId && intensity_level) {
        case (1): //...
        case (2): //...

        case (1): // same as above
        case (2): // same as above

        default:
        //...
   }

그래서 당연히 아래 두 사건은 절대 실행되지 않을 것이다. 그리고 문을 사용하는 것이 좋거나, 원한다면 중첩된 스위치를 사용하는 것이 좋습니다.

다음과 같은 작업을 수행할 수도 있습니다.

switch (exerciseId + " " + intensity_level) {
    case("1 1"): ...
    case("1 2"): ...
    case("2 1"): ...
    case("2 2"): ...



그러면 이제 논리 연산자를 사용할 수 있습니다.

switch (true) 
{
        case (1 && 1):
        this.header="Exercise 1 Level 1";
        this.instructions="Exercise 1 Level 1";
        break;
        case (1 && 2):
        this.header="Exercise 1 Level 2";
        this.instructions="Exercise 1 Level 2";
        break;  

        case (2 && 1):
        this.header="Exercise 2 Level 1";
        this.instructions="Exercise 2 Level 1";
        break;  
        case (2 && 2):
        this.header="Exercise 2 Level 2";
        this.instructions="Exercise 2 Level 2";
        break;

        default:
        this.header="Default";
        this.instructions="Default";
        break;
    }

반응형