April 8, 2019
Quick Tip: CF 2018 Array Negative Indices are Read Only
Comments
(0)
April 8, 2019
Quick Tip: CF 2018 Array Negative Indices are Read Only
Newbie 49 posts
Followers: 42 people
(0)

I came across something interesting this weekend.  I was given an array of values and needed to display them as a list.  For sake of example, here’s the type of array I was receiving:

variables.myArray = ['dog','cat','rabbit','fish'];

A simple arrayToList(variables.myArray) would result in: “dog,cat,rabbit,fish” which wasn’t ideal.  Ideally we wanted it to read “dog, cat, rabbit, and fish.”

Since we’re running on CF 2018 I thought, “array negative indexes to the rescue!” and I came up with this as a test:

<cfscript>
     variables.myArray = ['dog','cat','rabbit','fish'];
     writeDump(variables.myArray[-1]); // Outputs 'fish'
     variables.myArray[-1] = 'and ' & variables.myArray[-1];
     writeDump(arrayToList(variables.myArray,', ')); // Should be 'dog, cat, rabbit, and fish'
</cfscript>

This threw an error stating “Index -2 out-of-bounds for length 4”.  A quick discussion on the CFML Slack Channel revealed that it appears that you can not use a negative index as a target in setting a value.  While the above did not work, the following does:

<cfscript>
     variables.myArray = ['dog','cat','rabbit','fish'];
     writeDump(variables.myArray[-1]); // Outputs 'fish'
     variables.myArray[variables.myArray.len()] = 'and ' & variables.myArray[-1];
     writeDump(arrayToList(variables.myArray,', ')); // Outputs 'dog, cat, rabbit, and fish'
</cfscript>

Happy coding, everyone!

0 Comments
Add Comment