Getting element from an array where data may not exist

Viewed 83

I am trying loop over elements in an array

data = [];

data[3] = true;
data[4] = false;

for (i = 1; i <= data.len(); i++) {
    if(data[i])   {
        writeoutput("Kittens!")
    }
}

And I get an error

enter image description here

Not an option

My code is a simplification of larger process. The following is NOT an option

for (datum in data) {
    if(datum)   {
        writeoutput("Kittens!")
    }
}
3 Answers

Unless I've missed the point then that's what arrayIsDefined() is for, eg:

<cfscript>
data = [];

data[2] = javaCast( "null", 0 );
data[3] = true;
data[4] = false;

for (i = 1; i <= data.len(); i++) {
    if(arrayIsDefined(data,i) && data[i])   {
        writeoutput("Kittens!");
    }
}
</cfscript>

This fiddle demonstrates the above and confirms that it also safely handles the presence of an explicitly set null element in the array: https://cffiddle.org/app/file?filepath=97b96317-8dcd-4620-a953-2c895191a8dc/67ccc09d-f4b5-4a2e-93d6-4cf3269a29d3/19c13ebe-1af4-4c72-9d7c-4cb82fa58f13.cfm

Another approach is to use try/catch.

<cfscript>
data = [];

data[3] = true;
data[4] = false;
for (i = 1; i <= data.len(); i++) {
try {
    if(data[i])   {
        writeoutput("Kittens!" & i & "<br>")
    }
}
catch (any e) {
writeoutput("puppies " & i & "<br>");
}

}
</cfscript>
Related