What is the difference between
<cfscript>
i = []
i.push(1)
i = []
i.append(1)
</cfscript>
?
They both seem to have the same results.
CodePudding user response:
If you run this
<cfscript>
i = []
writedump(i.push(1)) // returns array length
writedump(i.append(1)) // returns array
</cfscript>
You can see that they give different responses.
CodePudding user response:
In addition to James A. Mohler's answer where the return value is different for each function, there's another distinction between the two. For append()
, there's also an additional optional boolean parameter merge
which if set to true
(default) will merge to the source array. If false, it will add the array as an additional element at the end. For your example of appending a single element to the array, setting the merge
parameter to either true or false changes nothing. However, if you're appending 2 arrays together, the difference is clear. For example
<cfscript>
i=[1,2,3,4,5];
i.append([6,7], true);
writeDump(i);
i=[1,2,3,4,5];
i.append([6,7], false);
writeDump(i);
</cfscript>
The first result will be: [1,2,3,4,5,6,7]
The second result will be: [1,2,3,4,5,[6,7]]
You can see the gist here.