为什么更新一个对象的属性会改变另一个对象?

Why does updating properties in one object change another object?(为什么更新一个对象的属性会改变另一个对象?)
本文介绍了为什么更新一个对象的属性会改变另一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过 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)

这篇关于为什么更新一个对象的属性会改变另一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)