Pages

Monday, 7 April 2014

AS3 Finding Index Position in an Array

Use the below script to find the index position in an array.

// Define an array of elements
var softwareList:Array = ["Photoshop", "Flash", "Dreamweaver", "Captivate", "Edge Animate", "Audition"];

// function to find index position in an array

function findIndexInArray(value:Object, arr:Array):Number
{
// create a softArr variable
var sortArr:Array = new Array();

// loops through the array (in this case softwareList Array)
for(var i:uint=0;i<arr.length;i++)
{
// pushes all the elements from the the softwareList Array to the sortArr
sortArr.push(i);
// checks for equality
if(arr[i]==value)
{
// returns the index value
return i;
}
}
// returns not a number if not matched
return NaN;
}

Create a for loop to use the function and within that store the index values in matchNum variable.


for(var i:uint=0;i<softwareList.length;i++)

{
var matchNum:Number = findIndexInArray(softwareList[i], softwareList);
trace(matchNum);
}

The Trace function produces the below result

0
1
2
3
4
5

No comments:

Post a Comment