2014-04-29 38 views
0

在JavaScript中我想提出的myArray有條件的內容(如果statment我猜使用。我已經試過這樣做,但都無濟於事。我想作一個JavaScript數組條件

我的一些代碼供參考:

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

你所說的「條件變量」是什麼意思? – Kyo

+0

@Kyo卡類型的變量,對不起。例如if(cardType ==「birthday」){then do this} – Acendor

回答

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..."]; 
+0

AHHH非常感謝你,現在我一直堅持這幾天。 – Acendor

+0

@ user3584008:我很樂意提供幫助。請考慮接受這個答案;-) – Cerbrus

+0

太容易了,再次感謝。 – Acendor