Array negative indexes in CF 2018 appear to be read only.
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!
You must be logged in to post a comment.