推入数组的 JavaScript 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14489860/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript object pushed into an array
提问by Kosmas Papadatos
Possible Duplicate:
How do I correctly clone a JavaScript object?
可能的重复:
如何正确克隆 JavaScript 对象?
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?
为什么会发生这种情况,我如何才能得到我期望的结果?
采纳答案by Ben McCormick
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 objalso points to, into the array.
JavaScript 数组保存对对象的引用,而不是对象本身。当您将对象推入数组时,它不会创建新对象,而只是将对该对象的引用(obj也指向该对象)放入数组中。
So in the end obj, temp[0], and temp1all 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"}
所以最终 obj、temp[0] 和 temp 1都指向同一个对象。要真正创建一个全新的对象,您可以使用Object.create()或 jQuery.extend({},obj)。尽管在您的情况下,只需使用创建一个新的简单对象就足够容易了var newobj = {name="2"}
回答by user1931858
JavaScript objects are passed by reference. In your case you have only one object "obj", and temp[0] and temp[1] are pointing to the same object.
JavaScript 对象是通过引用传递的。在您的情况下,您只有一个对象“obj”,并且 temp[0] 和 temp[1] 指向同一个对象。
回答by AlexandruSerban
objbeing an object is added by reference in the array so your actually adding the same objtwice.
obj作为对象是通过数组中的引用添加的,因此您实际上将相同的内容添加了obj两次。

