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

Javascript object reference linked to object in array? - Stack Overflow

programmeradmin5浏览0评论

If I have an object:

var array = [];
var theobject = null;

array.push({song:"The Song", artist:"The Artist"}, {song:"Another Song", artist:"Another Artist"});

and I do:

for(var i = 0; i < array.length; i++)
if(array[i].song == "The Song") {
theobject = array[i];
break;
}

If I then change theobject by doing:

theobject.song = "Changed Name";

I am having problems where despite myself trying to set ONLY "theobject.song" to be equal to "Changed Name", array[0].song bees set to "Changed Name" also.

What I want is "theobject.song" to bee "Changed Name" while array[0].song remains "The Song".

What is the best way to acplish this?

If I have an object:

var array = [];
var theobject = null;

array.push({song:"The Song", artist:"The Artist"}, {song:"Another Song", artist:"Another Artist"});

and I do:

for(var i = 0; i < array.length; i++)
if(array[i].song == "The Song") {
theobject = array[i];
break;
}

If I then change theobject by doing:

theobject.song = "Changed Name";

I am having problems where despite myself trying to set ONLY "theobject.song" to be equal to "Changed Name", array[0].song bees set to "Changed Name" also.

What I want is "theobject.song" to bee "Changed Name" while array[0].song remains "The Song".

What is the best way to acplish this?

Share Improve this question edited May 9, 2012 at 5:06 Rolando asked May 9, 2012 at 4:55 RolandoRolando 62.7k103 gold badges278 silver badges422 bronze badges 1
  • 3 Why don't you just try it out – blockhead Commented May 9, 2012 at 4:58
Add a ment  | 

2 Answers 2

Reset to default 9

You will never get a reference to your object in the loop. Try:

for(var i = 0; i < array.length; i++)
 if(array[i].song === "The Song") {
 theobject = array[i];
 break;
}

That will give a reference to the object, and you will be able to change the objects song property.

If you want to use a copy of the object, then you'll have to do a manual copy. E.g.

function clone(obj) {
  var copy = {};
  for (var attr in obj) {
   if (obj.hasOwnProperty(attr)) {
     copy[attr] = obj[attr];
   }
  }
  return copy;
}

And your loop bees:

for(var i = 0; i < array.length; i++)
 if(array[i].song === "The Song") {
 theobject = clone(array[i]);
 break;
}

It possible to use Object.assign() to only copy its value without the reference.

https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

var array = [];
var theobject = null;

array.push({
  song:"The Song", 
  artist:"The Artist"
  }, 
  {
  song:"Another Song", 
  artist:"Another Artist"
});

for(var i = 0; i < array.length; i++)
  if(array[i].song == "The Song") {
    theobject = Object.assign( {}, array[i] );
    break;
  }
  
theobject.song = "Changed Name";

console.log( array );
console.log( theobject );

发布评论

评论列表(0)

  1. 暂无评论