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 ?

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Janak
  • 4,986
  • 4
  • 27
  • 45

5 Answers5

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.

phihag
  • 278,196
  • 72
  • 453
  • 469
2

Try:

var Arr2 = Arr1.slice(0);

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

Stefan Dunn
  • 5,363
  • 7
  • 48
  • 84
2

You can try using Arr1.slice(0):

http://jsfiddle.net/L23nR/

MassivePenguin
  • 3,701
  • 4
  • 24
  • 46
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()

Prasath K
  • 4,950
  • 7
  • 23
  • 35
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.

Tim Heap
  • 1,671
  • 12
  • 11