7

I believe is something simple but obviously not simple enough :). Any ideas how to check if a value already exists in the Array before adding the value using FOR loop?

I have this so far and it doesn't work as I want to because the Array can contain duplicate values!

            var n:int = 5;
        var cnt:int;
        for (var i = 0; i < n; i++)
        {
            cnt = randomThief();

            for (var a = 0; a < loto5.length; a++)
            {
                if (loto5[i] == cnt)
                {
                    loto5[i] = cnt;
                }
            }
        }

2 Answers 2

18

You can use the indexOf() method of the Array class to check if the value exists like this :

var index:int = loto5.indexOf(cnt);

indexOf() returns a -1, if the value doesn't exist. Here is an example of how to do a check :

if (loto5.indexOf(cnt) >= 0)
{
   // do something
}
Sign up to request clarification or add additional context in comments.

Comments

1
for (var a = 0; a < loto5.length; a++)
{
    cnt = randomThief();
    if (loto5.indexOf(cnt) == -1) //if cnt isn't in array do ...
    {
        trace (cnt+" is not in Array");
        loto5[a] = cnt;
    }
}    

Works, simple and beauty :)

Comments

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.