Description

Loops over an array.

Returns

Nothing

Category

Syntax

arrayEach(array,function(any currentObj) {});

See also

Other array functions.

History

ColdFusion 11: Passing array index to callback functions.

ColdFusion 10: Added this function.

Parameters

Parameter

Description

array

Name of the array object.

function

Callback executed for each element in the array.

Basic example using the callback function

<cfscript>
       myCities=["London","New York","Paris","Tokyo","Barcelona"];
       // Create a function that takes city as an argument  and prints the name of the cities as output
       // with delimiter as space
       ArrayEach(myCities,function(city){
             WriteOutput(city & "  ");
             }
       );
</cfscript>

Output

London New York Paris Tokyo Barcelona

Passing array index to callback functions in ArrayEach

ColdFusion 10 supported passing objects in a callback function. In ColdFusion 11,  you could pass the index of an array to the callback function as shown below:

<cfscript> 
  cityArray = ["San Jose","New york","Boston", "Las Vegas"];
  
   function printArrayCity(city, index)
   {
         writeOutput("<br>" & city & "   is at index " &  index);
   }
  
   ArrayEach(cityArray ,printArrayCity);
  
</cfscript>

Output

San Jose is at index 1New york is at index 2Boston is at index 3Las Vegas is at index 4

Passing array to the closure function

Also, the original array can also be passed to the closure function. So the following code is also valid:

function printArrayCity(city, index, cityArray)
{
 
}
...

For example,

<cfapplication passarraybyreference="true">
<cfscript>
       cityArray=["London","New York","Paris","Tokyo","Barcelona"];
       function printArray(city,index,cityArray)
       {
       		cityArray[index] = city & " is visited.";
       }
       WriteOutput("The original array is:");
       WriteDump(cityArray);
       ArrayEach(cityArray,printArray);
       WriteOutput("The new array is:");
       WriteDump(cityArray);

</cfscript>

Output

ArrayEach

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License  Twitter™ and Facebook posts are not covered under the terms of Creative Commons.

Legal Notices   |   Online Privacy Policy