2

In one of my projects, I had to copy values of one array to another.

When i tried doing it this way :

 var Arr1 = new Array(1,2,3,4,5,6,7,8,9,10);
 var Arr2 = Arr1;        // will this create a pointer ??

Is it creating a pointer ?

Fiddle : I mean after the loop,if i try to access Arr1, it returns empty.

for(var i=0;i<Counter;i++)
{
    $('#testDiv').append(Arr2.pop() + " ");
}       
    alert("The element in other array : "  + Arr1);

Is there anything like pointer in javascript ?

3
  • Both Arr1 and Arr2 points to the same array Commented May 23, 2013 at 10:37
  • if i want to retain value of Arr1 and make changes to just Arr2 how do i do it ? Commented May 23, 2013 at 10:40
  • @janakshah stackoverflow.com/questions/7486085/… Commented May 23, 2013 at 10:41

5 Answers 5

3

Assignments in JavaScript indeed create a reference to the right hand side.

A pointer is a type of reference, but also has the following two properties:

  • It refers to a specific memory address.
  • One can add or subtract from it to get other memory addresses that are equally valid.

Both of these conditions are not met in plain JavaScript, although an implementation could surely provide a native function for these.

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

Comments

2

You can try using Arr1.slice(0):

http://jsfiddle.net/L23nR/

Comments

2

Try:

var Arr2 = Arr1.slice(0);

From here: http://davidwalsh.name/javascript-clone-array

Comments

1

In essence, yes. Values in JavaScript are references, so the variables Arr1 and Arr2 both refer to the same array instance in memory. All values are copied by reference upon assignment, so everything is a 'pointer' in JavaScript.

Comments

1

Replace

var Arr2 = Arr1; 

with

var Arr2 = Arr1.slice();

Check here : http://jsfiddle.net/dk7E6/

var Arr2 = Arr1;

This creates an array reference to Arr1 so if you modify Arr2 then Arr1 will be changed automatically .. So to get a copy of an array use array.slice()

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.