user2867054
user2867054

Reputation: 59

Javascript array changes after function without being involved

I'm confused. I have an array myArray = [2, 2, 2, 1, 1] and without knowing, it takes the values of the Array testArray.

if(count == 5) {
    alert("beginn" + myArray[2]);
    var testArray=testFunction(myArray);
    alert("middle" + myArray[2]);
    var testCount=countNumber(testArray);
    if (testCount = 3){
        count = 4;
    }
}

And here is the function:

function testFunction(testArray){
    var minimum=Math.min.apply(Math,testArray);
    var i=0;
    var position=-1;
    for(i;i<testArray.length;i++){
        if(position==-1){
            if(minimum==testArray[i]){
                position=i;
            }
        }
    }
    i = 0;
    for(i; i < testArray.length; i++){
        if(i != position){
            testArray[i] = testArray[i] - 1;
        }
    }

    return testArray;
}

So after the function testArray is correctly [1,1,1,1,0], but unfortunately also myArray and I don't know why.

Upvotes: 1

Views: 98

Answers (1)

elena a
elena a

Reputation: 79

In JavaScript, when you assign an array object to another variable you are basically assigning a pointer to the original array object. This means that if you do this:

var myArray = [1,2,3,4];
var testArray = myArray;

then any changes made to testArray will also be made to myArray because they are actually the same array!

To keep myArray from changing, you would need to pass a copy of the array:

var myCopy = myArray.slice(0);
var testArray=testFunction(myCopy);

Upvotes: 2

Related Questions