如果我有一个对象:
var array = [];
var theobject = null;
array.push({song:"The Song", artist:"The Artist"}, {song:"Another Song", artist:"Another Artist"});
Run Code Online (Sandbox Code Playgroud)
我这样做:
for(var i = 0; i < array.length; i++)
if(array[i].song == "The Song") {
theobject = array[i];
break;
}
Run Code Online (Sandbox Code Playgroud)
如果我然后通过执行以下操作来更改对象:
theobject.song = "Changed Name";
Run Code Online (Sandbox Code Playgroud)
我遇到了问题尽管我自己试图将"theobject.song"设置为等于"Changed Name",但数组[0] .song也设置为"Changed Name".
我想要的是"theobject.song"变为"Changed Name",而array [0] .song仍然是"The Song".
完成此任务的最佳方法是什么?
你永远不会在循环中获得对象的引用.尝试:
for(var i = 0; i < array.length; i++)
if(array[i].song === "The Song") {
theobject = array[i];
break;
}
Run Code Online (Sandbox Code Playgroud)
这将提供对象的引用,您将能够更改objects song属性.
如果要使用对象的副本,则必须进行手动复制.例如
function clone(obj) {
var copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
copy[attr] = obj[attr];
}
}
return copy;
}
Run Code Online (Sandbox Code Playgroud)
你的循环变成:
for(var i = 0; i < array.length; i++)
if(array[i].song === "The Song") {
theobject = clone(array[i]);
break;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12810 次 |
| 最近记录: |