0
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.

4
  • 2
    The question isn't clear Commented Mar 19, 2013 at 21:56
  • It's not clear what you're trying to do. What are you trying to do? You can't compare a string to an array like that. Commented Mar 19, 2013 at 21:58
  • sorry. really struggling to phrase things here. basically, if anyone types in the array values ("zero", "first"...), can the if or else statements be carried out. if (x..==n) just makes it so that when the letter "n" is typed into the prompt box the statements are carried out. Commented Mar 19, 2013 at 22:01
  • @LiamB Actually, x.toLowerCase() == n will not be true when the letter n is typed into the input box. n is an array of the strings "zero", "first", "second", and is not equal to the string "n". Just to recap, n is an array, x.toLowerCase() is a string that contains the lowercased input. You are checking whether a string equals an array, which is false. Commented Mar 19, 2013 at 22:03

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

4 Comments

+1, You're on a roll today. I can barely get a word in edgewise.
The indexOf() method is not supported in Internet Explorer 8 and earlier. Consider looping through the array or use one from a js library
thanks. the code works and you managed to understand my poorly phrased question. +1
@sshen That's true, added a link to an example shim.
0

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.