Global variable modified

as shown in the figure, a piece of code in the function, countData is a global variable, and the structure is roughly as follows

countData:{[message:[
              {time: "2018-08-03"},
              {time: "2018-08-03"}
                    ]
           ],
           [photo:[
              {time: "2018-08-03"},
              {time: "2018-08-07"},
              {time: "2018-08-07"},
              {time: "2018-08-07"}
           ]
           ]}

clipboard.png
clipboard.png

after the code of the first picture is executed, the processed listData, is obtained and the global variable countData is not equal to the initial countData
after the code of the second graph is executed, the global variable countData of the processed listData, is still the original value, which is the ideal result.

has assigned the global variable to the new variable and does not modify the global variable directly. Why does the code in the first diagram have an impact on the global variable?

Apr.07,2021

you should first know what is private and what is shared (holding the same reference)
figure 1.

var obj = {name:[1,2]};
var newObj = {};
newObj.name = obj.name;

above: name attribute this is newObj private but name value [1SCI 2] is obj and newObj share

//1. name
newObj.name = [1,3];
console.log(obj)//[1,2]
console.log(newObj)//[1,3]
//2. name
newObj.name[1] = 3;
console.log(obj)//[1,3]
console.log(newObj)//[1,3]

figure 2.

var obj = {name:[1,2]};
var newObj = obj;

above: assignment between objects newObj everything in obj shares
No matter how it is changed, it will affect each other

//1. 
newObj.name = [1,3];
console.log(obj)//[1,2]
console.log(newObj)//[1,3]
//2. 
newObj.name[1] = 3;
console.log(obj)//[1,3]
console.log(newObj)//[1,3]

"the global variable has been assigned to a new variable", which points to a object and is an address reference . When you assign countData to listData, they both point to the same address, so as long as listData changes, countData must change.

Menu