最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replacing an element in an object array - Stack Overflow

programmeradmin3浏览0评论

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?

I want to replace the entire object in an array.

http://jsfiddle.net/CWSbJ/

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?

Share Improve this question asked May 21, 2012 at 10:37 RolandGRolandG 1,3294 gold badges14 silver badges21 bronze badges 1
  • 1 You are just assigning an other value to element, not to array[0]. – Felix Kling Commented May 21, 2012 at 10:39
Add a comment  | 

2 Answers 2

Reset to default 16

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 variable with another object. This leaves the original array unmodified.

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

发布评论

评论列表(0)

  1. 暂无评论