EnglishAdam
EnglishAdam

Reputation: 1390

Copying an array produces strange results ('copying'==referencing)

EDIT: the problem I came across was that I did not know that js arrays are treated as objects and any as so are referenced not copied. If you were interested in simply reversing a js array you can use...reverse();

I thought I would be able to simply do the following in javascript

var originalArray = [1,2,3,5,8,13];
var originalArrayCOPY = originalArray;
console.log ("new copy = "+originalArrayCOPY);

for(var zyx = 0; zyx <6; zyx++){
    var xyz = 5-zyx;
    originalArray[zyx] = originalArrayCOPY[xyz];
}

console.log("original now "+originalArray);
console.log("copy ="+originalArrayCOPY);

But my results are so strange that I feel I must not understand javascript at all!!

new copy = 1,2,3,5,8,13

original now 13,8,5,5,8,13,

copy =13,8,5,5,8,13,

I can-t see why this wouldn-t work and I honestly am not sure why the COPY of the original array is changed at all.

If I could at least name the problem I could ask google, also if you tell me the name of the problem I will rename by SO question.

Upvotes: 0

Views: 43

Answers (1)

Edan Feiles
Edan Feiles

Reputation: 465

use this:

var originalArray = [1,2,3,5,8,13];
var originalArrayCOPY = originalArray.slice();
console.log ("new copy = "+originalArrayCOPY);
for(var zyx = 0; zyx <6; zyx++){
    var xyz = 5-zyx;
    originalArray[zyx] = originalArrayCOPY[xyz];
}

console.log("original now "+originalArray);
console.log("copy ="+originalArrayCOPY);

'=' copy references and slice() will produce a new copy of the array. see : https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

Upvotes: 2

Related Questions