在 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>
最佳答案
你可以这样做:
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...")}
如果满足前面的条件,这只会将特定项目添加到数组中。
例如,如果仅通过 yourName
和 personType
条件,myArray
将为:
["get", "idea..."];
关于javascript - 我想创建一个有条件的 javascript 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23358902/