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?

2
  • Are you sure you show us the code generating this log ? You don't even create an array here. Commented Nov 26, 2012 at 12:55
  • You dont have arrays in your code in first place. var items_to_send = sites_from_session;` where is second array? Commented Nov 26, 2012 at 12:55

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

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.