javascriptif-statementexecutionmultiple-results

Can there be multiple executions for an if statement?


Essentially, I want to have it so that

if(condition) {"do this" || "do that"};

Specifically, I'm having it so that if a specific div is set to a specific color (picked randomly from an array), then 1 of 4 other divs changes its color to a specific color.

Thanks!

EDIT: I guess I'm more wondering if I can randomize a 'then' statement. I'm making a game, so I want to avoid choosing which of the 4 divs I want to obtain the new color (which would mean every instance is scripted the same each time)


Solution

  • There can be many executions for an if statement. As much as you like. What you can do is use multiple if in that one if statement to select the proper div or use a switch instead. For example:

    var array = [3, 4, 1, 2];
    

    NOTE sometime what I do is shuffle the array, which mixes up the indexes, before randomly picking

    var my_array = array.sort(); // This will change your array, for example, from [3, 4, 1, 2] to [1, 2, 3, 4].
    or 
    var my_array = array.reverse(); // This will change your array, for example, from [3, 4, 1, 2] to [4, 3, 2, 1].
    
    var random_condition = Math.floor((Math.random() * 3)); // select at random from 0 to 3 because the array is ZERO based
    

    And then you do your logc:

    if(condition) {
        if (random_condition == 1 ) {
            "do this" with div 1 // array [0] == 1
        }
        else if (random_condition == 2 ) {
            "do this" with div 2 // array [1] == 2
        }
        else if (random_condition == 3 ) {
            "do that" with div 3 // array [2] == 3
        }
        else if (random_condition == 4 ) {
            "do that" with div 4 // array [3] == 4
        }
    }
    

    Or use a switch

    if(condition) {
        switch (random_condition) {
            CASE '1':
                "do this" with div 1 // array [0] == 1
                break;
            CASE '2':
                "do this" with div 2 // array [1] == 2
                break;
            CASE '3':
                "do this" with div 3 // array [2] == 3
                break;
            CASE '':
                "do this" with div 4 // array [3] == 4
                break;
            default
                // do nothing
                break;
        }
    }