Javascript 替换对象数组中的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10683692/
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
Replacing an element in an object array
提问by RolandG
I want to replace the entire object in an array.
我想替换数组中的整个对象。
var array = [ {name: "name1" }, { name: "name2" } ];
var element = array[0];
element = {name: "name3"};
alert(array[0].name);
In this piece of code I would expect the output name3, why can't I replace an entire object in an array like this? And what is the good way to do this?
在这段代码中,我希望输出 name3,为什么我不能像这样替换数组中的整个对象?这样做的好方法是什么?
回答by Jon
The correct way is
正确的方法是
array[0] = {name: "name3"};
Your existing code does not work as expected because you are taking a referenc* to the first element with
您现有的代码无法按预期工作,因为您将引用 * 引用到第一个元素
var element = array[0];
and then you are replacing the value of this local variablewith another object. This leaves the original array unmodified.
然后你用另一个对象替换这个局部变量的值。这使原始数组保持不变。
回答by Manse
Try this :
尝试这个 :
var array = [ {name: "name1" }, { name: "name2" } ];
array[0] = {name: "name3"};
alert(array[0].name);
element
is not the actual array - its a copy of the array
element
不是实际的数组 - 它是数组的副本