Programing

JavaScript에서 정수 범위 설정

lottogame 2020. 7. 12. 09:43
반응형

JavaScript에서 정수 범위 설정


나는 이런 식으로하고 싶다

    switch (this.dealer) {
        case 1-4: 
            // Do something.
            break;
        case 5-8: 
            // Do something.
            break;
        case 9-11: 
            // Do something.
            break;
        default:
            break;
    }

이것에 대한 올바른 구문은 무엇입니까? JavaScript로 가능합니까?

그래서 this.dealer정수이며, 그 값 사이에 있다면, 뭔가.


내가 알아 낸 또 다른 방법은 다음과 같습니다.

const x = this.dealer;
switch (true) {
    case (x < 5):
        alert("less than five");
        break;
    case (x < 9):
        alert("between 5 and 8");
        break;
    case (x < 12):
        alert("between 9 and 11");
        break;
    default:
        alert("none");
        break;
}

더 깨끗하게하기 위해 MarvinLabs의 답변을 늘리십시오.

var x = this.dealer;
switch (true) {
    case (x < 5):
        alert("less than five");
        break;
    case (x < 9):
        alert("between 5 and 8");
        break;
    case (x < 12):
        alert("between 9 and 11");
        break;
    default:
        alert("none");
        break;
}

break명령문이 나머지 경우를 건너 뛰도록 하기 때문에 범위의 하한값을 확인할 필요가 없으므로 실행 시간을 확인하는 시간이 지나면 (x <9) 값이 5 이상이어야한다는 것을 알 수 있습니다.

물론 사례가 원래 순서대로 유지되는 경우에만 출력이 정확하고 정수 값을 가정합니다 (질문에 명시된 바와 같이). 기술적으로 범위는 5와 8.999999999999 사이입니다 .j의 모든 숫자는 실제로 배정 밀도 부동이므로 포인트 번호.

사례를 이동하거나 각 사례 문에서 전체 범위를 볼 수 있도록 더 읽기 쉬운 경우 각 사례의 하위 범위에 대해 동일하지 않은 검사를 추가하십시오.

var x = this.dealer;
switch (true) {
    case (x < 5):
        alert("less than five");
        break;
    case (x >= 5 && x < 9):
        alert("between 5 and 8");
        break;
    case (x >= 9 && x < 12):
        alert("between 9 and 11");
        break;
    default:
        alert("none");
        break;
}

이로 인해 인적 오류가 발생한다는 점을 명심하십시오. 누군가가 범위를 업데이트하려고 할 때 범위를 변경하지 않아도 겹치거나 틈이 생기지 않도록 두 위치에서 변경하는 것을 잊지 마십시오. 예를 들어 여기서 8의 경우는 8과 일치하는 경우를 편집했을 때 아무것도 일치하지 않습니다.

    case (x >= 5 && x < 8):
        alert("between 5 and 7");
        break;
    case (x >= 9 && x < 12):
        alert("between 9 and 11");
        break;

    switch(this.dealer) {
        case 1:
        case 2:
        case 3:
        case 4:
            // Do something.
            break;
        case 5:
        case 6:
        case 7:
        case 8:
            // Do something.
            break;
        default:
            break;
    }

일련의 사례가 마음에 들지 않으면 간단히 if/else if/else진술하십시오.


This does not require a switch statement. It is much clearer, more concise, and faster to simply use if else statements...

var d = this.dealer;
if (1 <= d && d <= 11) { // making sure in range 1..11
    if (d <= 4) {
        alert("1 to 4");
    } else if (d <= 8) {
        alert("5 to 8");
    } else {
        alert("9 to 11");
    }
} else {
    alert("not in range");
}

Speed test

I was curious about the overhead of using a switch instead of the simpler if...else..., so I put together a jsFiddle to examine it... http://jsfiddle.net/17x9w1eL/

  • Chrome: switch was around 70% slower than if else

  • Firefox: switch was around 5% slower than if else

  • IE: switch was around 5% slower than if else

  • Safari: switch was around 95% slower than if else

Notes:

Assigning to the local variable is optional, especially if your code is going to be automatically optimised later.

For numeric ranges, I like to use this kind of construction...

if (1 <= d && d <= 11) {...}

... because to me it reads closer to the way you would express a range in maths (1 <= d <= 11), and when I'm reading the code, I can read that as "if d is between 1 and 11".

Clearer

A few people have commented that they don't think this is clearer. It's certainly not less clear as the structure is close to identical to the switch option. The main reason it is clearer is that every part of it is readable and makes simple intuitive sense, whereas "switch (true)" is a rather meaningless line of code. Many coders, reading that in your script, are going to go "WTF does that mean?" and then have to look it up. It's a dirty hack, it's not intuitive, and it's not clear. If that's how you like to code, and no one else is ever going to have to deal with your code base, then go for it, otherwise, it's better just to use the constructs for what they are intended.


If you need check ranges you are probably better off with if and else if statements, like so:

if (range > 0 && range < 5)
{
    // ..
}
else if (range > 5 && range < 9)
{
    // ..
}
else
{
    // Fall through
}

A switch could get large on bigger ranges.


No, this is not possible. The closest you can get is:

  switch(this.dealer) {
    case 1:
    case 2:
    case 3:
    case 4:
                      // DO SOMETHING
        break;
    case 5:
    case 6:
    case 7:
    case 8:
                      // DO SOMETHING
       break;

But this very unwieldly.

For cases like this it's usually better just to use a if/else if structure.


A more readable version of the ternary might look like:

var x = this.dealer;
alert(t < 1 || t > 11
  ? 'none'
    : t < 5
  ? 'less than five'
    : t <= 8
  ? 'between 5 and 8'
  : 'Between 9 and 11');

function sequentialSizes(val) {
 var answer = "";

 switch (val){
case 1:
case 2:
case 3:
case 4:
  answer="Less than five";
  break;
case 5:
case 6:
case 7:
case 8:
  answer="less than 9";
  break;
case 8:
case 10:
case 11:
  answer="More than 10";
  break;
 }

return answer;  
}

// Change this value to test you code to confirm ;)
sequentialSizes(1);

If you are trying to do something fast, efficient and readable, use a standard if...then...else structure like this:

var d = this.dealer;
if (d < 12) {
    if (d < 5) {
        alert("less than five");
    }else if (d < 9) {
        alert("between 5 and 8");
    }else{
        alert("between 9 and 11");
    }
}else{
    alert("none");
}

If you want to obfuscate it and make it awful (but small), try this:

var d=this.dealer;d<12?(d<5?alert("less than five"):d<9?alert("between 5 and 8"):alert("between 9 and 11")):alert("none");

BTW, the above code is a JavaScript if...then...else shorthand statement. It is a great example of how NOT to write code unless obfuscation or code minification is the goal. Be aware that code maintenance can be an issue if written this way. Very few people can easily read through it, if at all. The code size, however, is 50% smaller than the standard if...then...else without any loss of performance. This means that in larger codebases, minification like this can greatly speed code delivery across bandwidth constrained or high latency networks.

This, however, should not be considered a good answer. It is just an example of what CAN be done, not what SHOULD be done.

참고URL : https://stackoverflow.com/questions/5619832/switch-on-ranges-of-integers-in-javascript

반응형