1

Maybe I’m going about this all the wrong way, if so, please let me know!

Anyways, say I have an Array representing some nice data.

var orignal = ['a', 'b'];
var copy = orignal;
orignal.push('c');
console.log(original === copy);  // true

I kind of like this functionality where the to objects still are the same. Of course if I would set original = ['c'] that would not be the case anymore. Is there any pattern to let me do more things on the array without breaking the link?

cookie monster
  • 10,671
  • 4
  • 31
  • 45
  • 1
    why do you need an original and a copy if you want them both to be the same? – markasoftware May 07 '14 at 23:44
  • See http://stackoverflow.com/a/1232046/1470607 – Etheryte May 07 '14 at 23:46
  • The answer is no. You can't assign to the `original` variable and have it update the `copy` variable. There are no pointers in JavaScript. You can only mutate the object that `original` holds and view the changes from `copy`. This is because both hold a reference to the same Array, but that reference doesn't let you actually replace the actual structure in memory. – cookie monster May 07 '14 at 23:55
  • You might want to have a look at [this answer](http://stackoverflow.com/a/13349715/1048572) about mutating and non-mutating array methods – Bergi May 08 '14 at 01:04

2 Answers2

0

Assignment is the one thing that will break the link, because it is an operation on the reference, not the array. It makes the variable refer somewhere else. Anything else you do will be visible through both original and copy:

copy.length = 5; // visible through original
copy[3] = 4;     // visible through original
copy.pop();      // visible through original

If you think you want assignment to preserve the link, you should probably instead be doing some similar but distinct operation, such as filling an array with the contents of another.

Incidentally, it's probably a bad idea to call the variable copy, since it's not a copy. It's the original, just like original is.

user2357112
  • 260,549
  • 28
  • 431
  • 505
-1

You should do inheritance :

function inherits(base, extension)
{
   for ( var property in base )
   {
      try
      {
         extension[property] = base[property];
      }
      catch( warning ){}
   }
}

and then :

var original = ['a', 'b'];
var copy=[]; inherits(original,copy) //NOT : var copy = orignal;
original.push('c');
console.log(original === copy);  // false

DEMO : http://jsfiddle.net/abdennour/e64vB/1/

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254