![](/img/trans.png)
[英]How can I make an array or variable for an if statement in javascript?
[英]How can I use array variable in an if statement?
var n = new Array();
n[0] = "zero";
n[1] = "first";
n[2] = "second"
function myFunction() {
var x = prompt("Question?")
if (x.toLowerCase() == n) {
//code
} else {
//code
}
}
是否可以這樣做,以便在鍵入任何數組變量的情況下仍然執行if / else函數。
我猜你想檢查類型值是否存在於數組中? 如果是這樣的話:
function myFunction() {
var x = prompt("Question?")
if (n.indexOf(x.toLowerCase()) > -1) {
//code
} else {
//code
}
}
您需要支持IE8和更早版本,並且需要Array.prototype.indexOf的墊片(例如MDN提供的墊片)。
var n = new Array();
n[0] = "zero";
n[1] = "first";
n[2] = "second"
function myFunction()
{
var x=prompt("Question?")
for (var i in n) {
if (x.toLowerCase() === n[i] ){ alert("true"); }
}
}
myFunction();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.