6.3. Searching for Matching Elements in an Array

Problem

You want to find the first element in an array that matches a specified value.

Solution

Use a for statement to loop through an array, and use a break statement once a match has been found.

Discussion

When you are searching for the first element in an array that matches a specified value, you should use a for statement, as shown in Recipe 6.2, but with the addition of a break statement to exit the loop once the match has been found.

A break statement used within a for statement causes the loop to exit once it is encountered. Note that the break statement is generally placed within an if statement, so it is reached only when a certain condition is met. The importance of the break statement when searching for the first matching element is two-fold. First of all, you should not needlessly loop through the remaining elements of an array once the match has been found, since it would waste processing time. In the following example, the break statement exits the loop after the second iteration, saving six more needless iterations. Imagine the savings if there were a thousand more elements. Furthermore, the break statement is vital when searching for the first match because it ensures that only the first element is matched and that subsequent matches are ignored. If the break statement is omitted in the following example, all matching elements are displayed, as opposed to the first one only.

// Create an array with eight elements. myArray ...

Get Actionscript Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.