Javascript 对象引用链接到数组中的对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10510063/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:06:54  来源:igfitidea点击:

Javascript object reference linked to object in array?

javascript

提问by Rolando

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 becomes set to "Changed Name" also.

我遇到了问题,尽管我试图将 ONLY "theobject.song" 设置为等于 "Changed Name",但 array[0].song 也设置为 "Changed Name"。

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

我想要的是“theobject.song”成为“Changed Name”,而array[0].song 仍然是“The Song”。

What is the best way to accomplish this?

实现这一目标的最佳方法是什么?

采纳答案by KooiInc

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 songproperty.

这将提供对对象的引用,并且您将能够更改对象song属性。

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 becomes:

你的循环变成:

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

回答by Tarik Chakur

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

可以使用 Object.assign() 仅复制其值而无需引用。

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

https://developer.mozilla.org/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 );