简体   繁体   中英

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?

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();

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.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM