简体   繁体   中英

I would like to make a javascript array conditional

In JavaScript I would like to make the content of myArray conditional (I guess using an if statment. I have tried doing this but to no avail.

Some of my code for reference:

<?php 
    session_start();
    $theirname = $_GET['theirname'];
    $yourname = $_GET['yourname'];
    $slct2 = $_GET['slct2'];
    $slct1 = $_GET['slct1'];
?>

<script type="text/javascript">
    var theirName = "<?php echo $theirname; ?>";
    var yourName = "<?php echo $yourname; ?>";
    var cardType = "<?php echo $slct1; ?>";
    var personType = "<?php echo $slct2; ?>";

    var myArray=[
        "i need", 
        "to make the contents of ",  
        "this array",  
        "conditional",  
        "to the variable",  
        "cardType",  
        "and the variable",  
        "personType", 
    ];

    //shuffle array:
    myArray.sort(function(){return Math.round(Math.random());});

    //print to screen
    function printGreet(){
        document.getElementById('demo').innerHTML= [myArray.pop()];
    }
</script>

<div>
    <button onclick="printGreet()" class="large-btn" id="generate-Btn" rows="20">Generate</button>
</div>
<div id="yourMes">
    <p>Your message:</p>
</div>
<textarea name="text1" class="large-fld" id="demo"></textarea>

You can do it like this:

var myArray = [];

if(theirName  === "John"){ myArray.push("You")}
if(yourName   !== "Jane"){ myArray.push("get")}
if(cardType   >=   3    ){ myArray.push("the")}
if(personType ===  5    ){ myArray.push("idea...")}

This will only add the specific item to the array, if the condition preceding it is met.

For example, if only the yourName and personType conditions pass, myArray will be:

["get", "idea..."];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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