Search code examples
arraysactionscript-3loopsfor-loop

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;
                }
            }
        }

Solution

  • 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
    }