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?
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.
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.