0

Short summary: I have written some code that fills up a 2-dimensional array. When I display this array, everything is perfect. Now I give this 2d-array as a parameter to a function. When I call the function inside of

document.getElementById('output').innerHTML = myFunction(int, array);

it shows exactly the right values. However, I don't want to display them, I want to further use them. As the function returns an array (one dimensional), I tried

var my_result_array = myFunction(int, array);

I have also tried push() and pre-defined arrays or accessing just single elements.

The thing is, as soon as I have the function called in my document, the array I am giving to the function as a parameter is changing! I took care that there are no similiar names, but I just can`t figure out, why it is always changing my parameter array, therefore destroying the calculation but working fine if I use it in the document.getElementbyId part.

Any suggestions?

Edit for more code: I try to keep it short and explainatory. I am creating an empty array with a dimension given by mat_dimension_js

var berechnungs_array = new Array(mat_dimension_js);
    for (var i = 0; i < mat_dimension_js; i++){ 
        berechnungs_array[i] = new Array(mat_dimension_js);
    }

I then fill this array up with values. If I print the array, everything is fine, the values are where they belong. I then feed this array to myFunction()

Sorry for the mess, I have also tried it without creating an array A again. I then try to grab the output of myFunction() as told above, but as soon as I do that, somehow the array I have given as a parameter changes.

Tim
  • 43
  • 5

1 Answers1

0

Arrays in JavaScript are passed by reference, meaning that any changes you do to the array passed inside the function will also be saved in the actual array.

In addition, A = mat_array; does not create a copy of mat_array, but another pointer to it (meaning that both variables refer to the exact same array object internally).

To properly make a copy of a 1D array, calling .slice(0) should do the trick. However, for 2D arrays, you need to do this recursively.

See Javascript passing arrays to functions by value, leaving original array unaltered

What is the most efficient way to deep clone an object in JavaScript?

Anis R.
  • 6,656
  • 2
  • 15
  • 37
  • 1
    Thank you! I cloned the array inside the function I am calling instead of referencing it by ``` var A = []; for (var i = 0; i < array_param.length; i++) A[i] = array_param[i].slice(); ``` Worked like a charm! Thanks! – Tim May 09 '19 at 09:54