0

I have simple code

sites_from_session = 12;
function function_name () {
    var items_to_send = sites_from_session;
    var template_name = jQuery('#new-site-template-name').val();
    console.log(sites_from_session);
    items_to_send.push(template_name);
    console.log(sites_from_session);
}


function_name();
function_name();
function_name();
function_name();
function_name();
function_name();//...

The problem is that the push method pushes value to both arrays

enter image description here

Where i am wrong?

Kin
  • 4,466
  • 13
  • 54
  • 106

2 Answers2

1

Arrays do not self clone in JavaScript. When you say something like

arr1 = arr2;

where both arr2 is a valid array, you haven't made an actual copy of arr2. All you've done is create a reference pointer to it for arr1. So when you make a change like

arr1[0] = "some value";

you are (in essence) saying the same thing as

arr2[0] = "some value";

To properly clone a separate copy you need to use this:

var items_to_send = sites_from_session.slice();

This will return a new array that holds all of the items from the original array.

Joel Etherton
  • 37,325
  • 10
  • 89
  • 104
0

It is a very common Javascript problem. The arrays are not copied like this:

var items_to_send = sites_from_session;

It merely copies the reference of the array to a new variable. In other words, items_to_send and sites_from_session are two names pointing to the same array in RAM. If you want to make a copy of the array (called deep copying) rather than just another pointer (shallow copying), you need to use slice():

//create a copy of the array
var items_to_send = sites_from_session.slice(0);

The rest of your code should work fine.

Possible duplication of this question: How do you clone an Array of Objects in Javascript?

You can learn more here: http://davidwalsh.name/javascript-clone-array

Community
  • 1
  • 1
AlexStack
  • 16,766
  • 21
  • 72
  • 104