user2166577
user2166577

Reputation:

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

Is it possible to make it so that if any of the array variables are typed in, the if / else function is still carried out.

Upvotes: 0

Views: 515

Answers (3)

bfavaretto
bfavaretto

Reputation: 71918

I'm guessing you want to check if the typed value exists in the array? If so:

function myFunction() {
    var x = prompt("Question?")
    if (n.indexOf(x.toLowerCase()) > -1) {
        //code
    } else {
        //code
    }
}

You you need to support IE8 and earlier, you'll need a shim for Array.prototype.indexOf (for example, the one provided by MDN).

Upvotes: 3

The Internet
The Internet

Reputation: 8103

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();

Upvotes: 0

Philipp
Philipp

Reputation: 69663

Depending on if you want the condition to be true on every array element or just on at least one, you can use n.every or n.some.

Upvotes: 0

Related Questions