0

i want check if random variable is equal to some numbers do something

for example i have 16 number that i want check them is equal to random number or not

var randomNum = Math.floor(Math.random() * (192 - 1+ 1) + 1)
if (randomNum == 1 ||  randomNum == 24 ||  randomNum == 25 ||  randomNum == 48 ||  randomNum == 49 ||  randomNum == 72 ||  randomNum == 73  ||  randomNum == 96 ||  randomNum == 97 ||  randomNum == 120 ||  randomNum == 121 ||  randomNum == 144 ||  randomNum == 145 ||  randomNum == 168 ||  randomNum == 169 )
{
    blnRand=true;
}
else
{
    blnRand=false;
}

It's very bad way for check my variable I wanna a short code like this:

if (randomNum == 1,24,25,48,49,72,73,96,97,120,121,144,145,168,169)
   blnRand=true;
else
   blnRand=false;

but don't work too, how can write short code for the if statement in here

0

1 Answer 1

2

"Best" is subjective and depends a lot on how you're using it; you have a few choices:

  1. A switch statement:

    switch (randomNum) {
        case 1:
        case 24:
        case 25:
        //...
           blnRand = true;
           break;
        default:
           blnRand = false;
           break;
    }
    
  2. An array:

    var answers = [1, 24, 25/*...*/];
    blnRand = answers.indexOf(randomNum) !== -1;
    
  3. A lookup object:

    var answers = {
        1: true,
        24: true,
        25: true,
        // ...
    };
    blnRand = answers[randomNum] || false;
    
  4. A lookup Set (ES6 and higher only):

    var answers = new Set([1, 24, 25/*...*/]);
    blnRand = answers.has(randomNum);
    
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much @T.J. Crowder, It is very short and powerful answer to my question, of course i think array way is very better than

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.