问题描述
我通过ajax将JSON数据加载到对象,将该对象复制到新对象(initData和newData)。当我改变newData的属性时,initData的属性也改变。为什么会发生这种情况?
I'm loading JSON data into an object via ajax, copying that object to new objects (initData and newData). When I change the property of newData, the property of initData also changes. Why is this happening?
var initData = {};
var newData = {};
function load_data(NDB_No){
$.getJSON(('scripts/jsonencode.php?q=' + NDB_No), function(data) {
for (prop in data){
initData[prop] = data[prop];
newData[prop] = data[prop];
}
console.log('init data: ' + initData.properties.Protein); // "init data: 0.259"
console.log('new data: ' + newData.properties.Protein); // "new data: 0.259"
var n = parseFloat(newData.properties.Protein);
newData.properties.Protein = n+1;
console.log('init data: ' + initData.properties.Protein + 'new data: ' + newData.properties.Protein);
// "init data: 1.259 new data: 1.259"
// why are these the same when I only updated newData object?
});
}
推荐答案
它看起来像 data [prop]
是一个对象(因为你以后指的是 newData.properties.Protein
)。对象总是通过引用传递,而变量只是一个指向它的指针。
It looks like data[prop]
is an object (since you are later referring to newData.properties.Protein
). Objects are always passed by reference, with the variable just being a pointer to it.
由于你首先获得JSON,你的对象是JSON能力的,因此您可以使用它来克隆对象:
Since you're getting JSON in the first place, your object is JSON-able, so you can use that to "clone" the object:
$.getJSON(...,function(data) {
initData = JSON.parse(JSON.stringify(data));
newData = JSON.parse(JSON.stringify(data));
});
这将确保对象是独立的。还有其他方法可以做到这一点,但这个避免手动递归通过使用内置的方法(总是更快)
This will ensure that the objects are separate. There are other ways to do this, but this one avoids the manual recursion by using built-in methods (always faster)
这篇关于为什么更新一个对象中的属性会更改另一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!