我想使一个javascript数组有条件

时间:2014-04-29 08:00:59

标签: javascript

在JavaScript中我想使myArray的内容有条件(我猜是使用if语句。我试过这样做但是没有用。

我的一些代码供参考:

<?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>

1 个答案:

答案 0 :(得分:3)

你可以这样做:

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...")}

如果满足前面的条件,这只会将特定项添加到数组中。

例如,如果只有yourNamepersonType条件通过,则myArray将为:

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