August 30, 2007

August 22, 2007

Loops

Here's a little "gotcha" that I ran across recently. The following code snippet deletes all of the elements in an array called myArray if they are not greater than zero:.


for (i = 1; i LTE ArrayLen(myArray); i = i + 1) {
     if (myArray[i] LTE 0) {
          ArrayDeleteAt(myArray, i);
     }
}

A bit of background for those that are not familiar with ColdFusion Script.

  • The length of an array in ColdFusion is dynamic
  • ArrayLen() returns the length of an array
  • ArrayDeleteAt() deletes the element from the array at the specified index
  • LTE means "Less Than or Equal"; just like <=

At first glance it appears as though this bit of code should work, but in practice it does not. The reason is due to the fact that when an element is removed from myArray the length of the array changes. Therefore as elements are deleted from the array the terminating condition of the for loop may be satisfied before all of the elements in the array are compared.

I will leave the alternative as an exercise for the reader.

links for 2007-08-22

August 8, 2007

links for 2007-08-08

August 1, 2007