0

I've got one peculiar problem while working on with javascript. I have a temporary variable where I had stored a value while loading the page. Then I had to perform some filtering of data for some events, so I had assigned it to another variable and performed the filter like this:

var myVar = tempVar;

myVar is a new variable and initially tempvar has two array elements. After filtering I will be assigning the value to myVar. The strange thing occurs now. While myVar value changes, automatically tempVar value also changes. Do anyone know why this happens? If so can you tell me how to assign the variable value to another variable and perform operation without changing the variable's value?

3
  • these information is not enough, please share your code Commented Jun 3, 2014 at 6:44
  • post your code. many things are not clear unless you post your code here Commented Jun 3, 2014 at 6:47
  • You have to create a copy of the value hold in tempVar. How to do this exactly depends on the "type" of the value. Commented Jun 3, 2014 at 7:00

2 Answers 2

2

This is because your are creating a reference to the array in the new variable, not copying it. Therefore both myVar and tempVar are pointing to the same variable.

To clone an array use slice(0):

var myVar = tempVar.slice(0);

Working example

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

2 Comments

tempVar contains a array object.Now when i put slice(0) it throws an error like this "undefined is not a function"
@user2078883: If you get that error then you are not working with an array, like you claimed.
0

As stated above, myVar = tempVar simply matches the object references to each other so they share the same object.

If you wish to clone an object using jQuery, you can use the jQuery extend option

var myVar = jQuery.extend(false, {}, tempVar);  // shallow Copy
var myVar = jQuery.extend(true, {}, tempVar);   // deep Copy

If your definition of objectToCopy was

var tempVar= {
   var item1 = 1;
   var item2 = 2;
   var deeperItem = {
        var item3 = 3
   }
}

A shallow copy would clone the first layer of data into the myVar .

Any changes to the tempVar item1,item2 would be independent of the myVar item1,item2.

However, any nested objects (like deeperItem), would still be linked, so myVar .deeperItem.item3 = 'New Value' would also set myVar .deeperItem.item3

If you want a full clone using jQuery, use the second method, which does a deep copy so its a completely seperate object.

http://api.jquery.com/jquery.extend/

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.