1

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.

6
  • 1
    Please stop using those horrible german function names. Not only are they not english, they are also WAY too verbose. (I'm german myself, so it's not "some stupid american" complaining ;)) Commented Jul 21, 2014 at 22:07
  • 4
    This happens because arrays in javascript are passed by reference, if you want to pass them by value, use var testArray = testFunction(myArray.slice());, also, indent your code. (= Commented Jul 21, 2014 at 22:14
  • Aren't arrays passed by reference in javascript? That would mean you're returning an array here, but also modifying the original since that's what you're referring to from within your function. Commented Jul 21, 2014 at 22:15
  • Don't you mean to say if (testCount == 3) Commented Jul 21, 2014 at 22:16
  • also watchout for that 'if(testCount=3)': you are assigning value 3 to testCount var, not checking its value Commented Jul 21, 2014 at 22:16

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.