JavaScript对象被推入数组 [英] JavaScript object pushed into an array
问题描述
可能重复:
我如何正确克隆一个JavaScript对象?
我有这段代码:
var temp = [];
var obj = {name:1};
temp.push(obj);
obj.name =2;
temp.push(obj);
我期待的是真实的:
temp [0] .name ==1&& temp [1] .name ==2;
实际发生的事情:
temp [0] .name ==2&& temp [1] .name ==2;
为什么会发生这种情况,以及我如何得到我期待的结果?
JavaScript数组包含对象的引用,而不是对象本身。将对象推入数组时,它不会创建新对象,但它只是将对象的引用( obj
也指向)放入数组中。 / p>
所以最后obj,temp [0]和temp 1 都指向同一个对象。要实际创建一个全新的对象,您可以使用对象.create()或jQuery.extend({},obj)。虽然在你的情况下,只需使用 var newobj = {name =2}
创建一个新的简单对象就够了
Possible Duplicate:
How do I correctly clone a JavaScript object?
I have this code:
var temp = [];
var obj = {name:"1"};
temp.push(obj);
obj.name = "2";
temp.push(obj);
What I'm expecting to be true:
temp[0].name == "1" && temp[1].name == "2";
What actually happens:
temp[0].name == "2" && temp[1].name == "2";
Why does this happen, and how I can get what I'm expecting?
JavaScript arrays hold references to objects, rather than objects themselves. When you push an object into the array it does not create a new object, but it simply puts a reference to the object, that obj
also points to, into the array.
So in the end obj, temp[0], and temp1 all point to the same object. To actually create a completely new object, you can use Object.create() or jQuery.extend({},obj). Though in your case it's easy enough just to create a new simple object using var newobj = {name="2"}
这篇关于JavaScript对象被推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!