简体   繁体   中英

Why does this javascript function create a deep copy instead of a shallow copy?

This is the code and according to a book I'm reading, it states that arr2 can be a deep copy, meaning new memory is allocated to store the object, which in this case is arr2 .

function copy(arr1, arr2) {
    for (var i = 0; i < arr1.length; ++i) {
        arr2[i] = arr1[i];
    }
}

It's not a deep copy. Yes, new memory is allocated for the array itself and its elements, but if objects are part of the array, they are copied as references. New objects are not created.

If it were a deep copy, changing an object stored in arr1 wouldn't change the corresponding object copied into arr2 , but it does:

 function copy(arr1, arr2) { for (var i = 0; i < arr1.length; ++i) { arr2[i] = arr1[i]; } } var arr1 = [1, 2, { 'foo': 'bar' }]; var arr2 = []; copy(arr1, arr2); console.dir(arr1); console.dir(arr2); arr1[2].foo = 'changed'; console.dir(arr1); // changed, of course console.dir(arr2); // also changed. shallow copy. 

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