Why does the original array change?

Based on Coldfusion documentation ... " Arrays are passed to user functions by value, so the function receives a new copy of the array data and the array on the calling page is not changed by the function. "

So, I am working on a small practical project. First I take a list of numbers, converting it to an array (which I call cardArray), then sort the array and finally passing the array to a pair of UDFs that will look for different patterns in numbers and manipulate (if necessary) the argument (also known as the passed array )

I never reference the source array in UDF, I only refer to the name of the argument. However ... if I cfdump the original array after calling the functions, my original array was modified. Can someone tell me why?

I'm sure I can get around this. So this is not my big problem. My problem is that this behavior is completely contrary to the way I β€œthought” that it would work, and it drives me crazy!

    function hasPair(pairArray) {
        pairCount = 0;
        for (i=2; i lte arrayLen(pairArray); i++){
            if(pairArray[i] is pairArray[i-1]){
                pairCount++
                arrayDeleteAt(pairArray, i)
                arrayDeleteAt(pairArray, i-1)
                i=2
            }
        }
        return pairCount;
    }

    function hasStraight(straightArray){
        sequenceCards = 0;
        for (i=2; i lte arrayLen(straightArray); i++){
            if(straightArray[i] - straightArray[i-1] is 1){
                sequenceCards++
            }
        }
        if (sequenceCards GTE 4){
            return 1;
        }
        else{
            return 0;
        }
    }

</cfscript>

<cfoutput>
    <cfset cardList = "5,6,7,8,10,8,9">
    <cfset cardArray = listToArray(cardList)>
    <cfdump var="#cardArray#" label="Original Array Before">
    <cfset arraySort(cardArray, "numeric", "desc")>
     #hasPair(cardArray)# <br/> 
     #hasStraight(cardArray)# <br/> 
    <cfdump var="#cardArray#" label="Original Array After">
</cfoutput>

Results in:

The original array BEFORE the function call [6,6,7,8,10,8,9].

The original array AFTER the function call [10,9,7,6,5]

( , ). , 8s . . 8s arrayDeleteAt (pairArray, i) arrayDeleteAt (pairArray, i-1) . (pairArray), ( ).

+4
2

Lucee, , , Lucee, Adobe. Lucee Adobe; , .

+7

, . <cfset arrayCopy = originalArray>, arrayCopy , . , :

<cfset arrayCopy = Duplicate(originalArray)>
+1

All Articles