user3392537
user3392537

Reputation: 11

Check if exists in Array

I'm creating a program in Flash using Actionscript 3. I was woundering if I could write an «if-statement» that checks if the text the user inputs is already in an array.

Like, if you have an array:

var alphabet:Array = new Array("a","b","c","d","e")

I want to make a statement like

If ('a' exist in alphabet)

Is there any way I can do that?

Upvotes: 0

Views: 212

Answers (2)

konsnos
konsnos

Reputation: 34

If your array is filled with random entries, you should parse the array one by one.

You can create a function which you supply the parameters of the array and the string you search for like this one.

static public function checkIfExists(txt:String, array:Array):Boolean 
{
    for (var i:int = 0; i < array.length; i++) 
    {
        if (array[i] == txt) 
        {
            return true;
        }
    }
    return false;
}

Then you can call it by

checkIfExists('a', alphabet);

Upvotes: 0

Andrey Popov
Andrey Popov

Reputation: 7510

You can use indexOf to find if the element is in the Array:

if (alphabet.indexOf('c') != -1) {
    // the element is there
}

indexOf actually returns the position at which the element is found, and -1 if the element is missing. So this is a simple check.

Upvotes: 4

Related Questions