简体   繁体   中英

JavaScript scoping (copying one array to another)

In this code... mapObj.fetchTimeObjs should NOT change right?!?!
Somehow mapObj.fetchTimeObjs gets changed when this function is run:

function clockErasePast(){
    var now = new Date().getTime();
    var tmpFetchTimeObjs = [];
    for(var i =0; i<mapObj.fetchTimeObjs.length; i++){
        tmpFetchTimeObjs.push(mapObj.fetchTimeObjs[i]);
        if(mapObj.fetchTimeObjs[i].start < now){tmpFetchTimeObjs[i].start = now;}
    }
    return tmpFetchTimeObjs;
}

tmpFetchTimeObjs[i] will contain only reference to the mapObj.fetchTimeObjs[i] .

If you will change tmpFetchTimeObjs[i] , the mapObj.fetchTimeObjs[i] will be changed, because you will have only one object which has two references. And if it will changed from one reference, it will be changed for the second reference too.

Let's consider an object which has two references. Here I change the object from one reference, and get the update for the second reference, because they refer to the same object.

 var objA = { name: 'Bob', age: 25}; var objB = objA; objB.age = 30; console.log(objA.age); 

To get independent object you need to create them. You can use Object.assign() function, which will copy any enumerable properties from into the destination(first parameter) object and returns it.

You can create with

var obj = Object.assign({}, mapObj.fetchTimeObjs[i]);
tmpFetchTimeObjs.push(obj);

The objects you push to the new array, are the same as the original array has, so if you mutate them, that mutation is visible to both arrays. This is what is called doing a shallow copy.

You could make a copy at one deeper level, where you would also create new objects and copy the original object's properties (like start ) into those new objects. This you can easily do with Object.assign :

    tmpFetchTimeObjs.push(Object.assign({}, mapObj.fetchTimeObjs[i]));

If these objects themselves have nested objects, then the problem you had would occur at deeper levels. If this is an issue, then you should look to deep clone solutions, like provided in this Q&A .

You need to clone the TimeObjs , since variables only keep the reference to the TimeObjs . We don't know the structure of your TimeObjs , so if the TimeObjs doesn't contain other objects, Object.assign() will work, otherwise maybe you need a deep clone method, such as jQuery.extend() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM