【问题标题】:Javascript object reference linked to object in array?Javascript对象引用链接到数组中的对象?
【发布时间】:2012-05-09 04:55:58
【问题描述】:

如果我有一个对象:

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 = array[i];
break;
}

如果我通过以下方式更改对象:

theobject.song = "Changed Name";

我遇到了一些问题,尽管我自己尝试仅将“theobject.song”设置为等于“Changed Name”,但 array[0].song 也设置为“Changed Name”。

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

最好的方法是什么?

【问题讨论】:

  • 你为什么不试试看

标签: javascript


【解决方案1】:

你永远不会在循环中获得对你的对象的引用。试试:

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

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

如果您想使用对象的副本,则必须手动复制。例如

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

你的循环变成:

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

【讨论】:

  • 我不要引用,我要副本。我只想更改对象的歌曲属性,而不是原始数组。
【解决方案2】:

可以使用 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 );

【讨论】:

    猜你喜欢
    • 2022-09-26
    • 2021-12-04
    • 1970-01-01
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-17
    • 1970-01-01
    相关资源
    最近更新 更多