me_digvijay
me_digvijay

Reputation: 5502

Why splice() method changes the value of other array?

I have an array say

var list = ["first", "second"];

now I assign list to some other variable say

var temp = list;

Now when I use splice on list like

list.splice(0,1);

Now when I check the value of list it shows

list = ["second"]

Also when I check the value of temp then it says

temp = ["second"]

I want to know why is that so? Why the value of temp is changed?

Upvotes: 5

Views: 5763

Answers (4)

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123438

when you do an assignment like var temp = list you're creating a reference temp to list. So since splice changes list array in-place, you're also changing temp

Use slice instead which returns a copy of the array, like so

var temp = list.slice();

Upvotes: 8

Scott
Scott

Reputation: 2793

You can use a prototype method to add this functionality.

Object.prototype.clone = function() {
  var newObj = (this instanceof Array) ? [] : {};
  for (i in this) {
    if (i == 'clone') continue;
    if (this[i] && typeof this[i] == "object") {
      newObj[i] = this[i].clone();
    } else newObj[i] = this[i]
  } return newObj;
};

Which then allows you to do this:

var a = [1,2,3];

var b = a.clone();

a[1] = 5;

console.log(a); //1,5,3
console.log(b); //1,2,3

Disclaimer: shamelessly borrowed from here (the whole article is worth a read): http://my.opera.com/GreyWyvern/blog/show.dml/1725165

Upvotes: 0

mplungjan
mplungjan

Reputation: 178421

slice

should do the trick:

var temp = list.slice(0);

About object cloning, look here How do you clone an Array of Objects in Javascript?

Upvotes: 1

John Green
John Green

Reputation: 13445

A common mistake in JS

This is a pointer, not a clone of the object:

var temp = list;

If you want to actually copy the object, there are a few ways. The simplest is just to concat it with itself:

var temp = list.concat([]);
// or
var temp = list.slice();

Note that this is somewhat dangerous, it only gets the base values out of the array. There are more advanced methods for cloning objects and creating 'perfect' array clones.

Upvotes: 1

Related Questions