4
var y=document.forms["form"]["user"].value
    if (y==null || y=="" )
        {
            alert("Username cannot be Blank");
            return false;
        };

var x = new Array();
    x[0] = "bill";  
    x[1] = "ted";   
    x[2] = "jim";   
    for ( keyVar in x ) 
        {
            if (x==y)
            {
                alert("Username Taken");
                return false;
            };

        };

How do I compare a variable to that in a JavaScript array, I managed to make the example above, but the second part, the bit I need, doesn't work. any ideas ?

3 Answers 3

4

You can simply check an array with the Array.prototype.indexOf method.

var x = [ 'bill', 'ted', 'jim' ],
    y = 'ted';

if( x.indexOf( y ) > -1 ) {
    alert('Username Taken');
    return false;
}
Sign up to request clarification or add additional context in comments.

3 Comments

I think that indexOf is much slower than checking if the property of an object is true (and this get more relevant as the array grows in size)
@Nicola this is probably the most straight forward answer since the OP wants to search against an array. If the array was sorted then we could use a binary search. Otherwise, using an object would probably yield better results... (keys/values, TRIE etc)
@NicolaPeluchetti: the array would need to become really huge before performance becomes an issue. However, ES.next will solve all the problems, weakmaps are coming :)
3

You should use an object instead:

var y = document.forms["form"]["user"].value;
if (y == null || y == "") {
    alert("Username cannot be Blank");
    return false;
};

var x = {};
x["bill"] = true;
x["ted"] = true;
x["jim"] = true;
if (x[y] === true) {
    alert("Username Taken");
    return false;
}

Comments

3

You can do this quite simply with jQuery

The list of the array values

var x = new Array();
x[0] = "bill";  
x[1] = "ted";   
x[2] = "jim";

then

 if(jQuery.inArray("John", arr) == -1){
     alert("Username Taken");
 }

1 Comment

There is no jQuery involved here i think

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.