Paul
Paul

Reputation: 6176

javascript array attributes passed by reference

in this example, it seems that we can use a variable (here "second") to fill the array myArray, as if second was a "reference" to myArray : is that really what happens here?

var myArray = [];
var second = myArray;
    second.target = … //we fill the "second" variable
    second.offsetX = …
    second.offsetY = …

var target = myArray.target; //then we retrieve the result from myArray
if (target) {

Thanks

Upvotes: 0

Views: 422

Answers (4)

Umesh Patil
Umesh Patil

Reputation: 10685

var myArray = []; 

This is just an array declaration It is same as var myArray=new Array();

About Array Referencing:

var second = myArray; 

We are pointing the variable second to myArray memory location. Here new Object second will be created point to content of myArray. So, if you read content of second. It will read the myArray. But, you edit/update the content of second, content of myArray will be copied into second and it will be modified. As Bakudan said, It is the shallow copy. See the example below,

var myArray=[10,20,30];
var second =myArray; //second will contain 23,45 and 100.

If we update the array second, second=[100,200,300] Original contents will be cleaned and 100,200,300 will be written.

To append the content to array second without removing the original content, We need to use function push as below:

second.push(100);second.push(200),second.push(300);

Now, content of second will be 10,20,30,100,200,300.

Object Property:

second.target = "testString";
second.offsetX =87;
second.offsetY =56;

This is the creation of object properties. It is same as,

second={"target":"testString","offsetX":87,"offsetY":56};

If you want to access value 87, it can be accessed as second.offsetX or second[offsetX].

More Information about java script Array is available here.

Upvotes: 1

Bakudan
Bakudan

Reputation: 19492

This is called a shallow copy. You have a reference (var second = ...) to the original array (var myArray = ...), they both are pointing to the same memory in the memory of the JavaScript virtual machine.

This way you can access the array either by second or myArray.

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

Yes, this is exactly what happens here. When you (for example) push new elements to second, you can read them later from myArray.

BTW, I sense that you're doing something strange. Why do you set an offsetX on an array?

Upvotes: 1

Adam Rackis
Adam Rackis

Reputation: 83356

second was a "reference" to myArray : is that really what happens here?

Yes.

Objects—like arrays—in JavaScript are passed and assigned by reference.

From your example, myArray and second both point to the same object in memory.

Upvotes: 2

Related Questions