Quick Tip: CF 2018 Array Negative Indices are Read Only

April 8, 2019
Wizard 25 posts
Followers: 13 people
0

Quick Tip: CF 2018 Array Negative Indices are Read Only

Wizard 25 posts
Followers: 13 people
April 8, 2019

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!

Comments (0)
Add your comment