Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AS3: How to check if a value already exists in the Array before adding with FOR loop?

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;
                }
            }
        }
like image 729
irnik Avatar asked Apr 18 '13 17:04

irnik


2 Answers

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
}
like image 141
prototypical Avatar answered Sep 28 '22 18:09

prototypical


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

like image 30
irnik Avatar answered Sep 28 '22 20:09

irnik