简体   繁体   中英

angular js - copy object without their reference being copied

I need to make a copy of an array in javascript such that the addresses of both arrays should be different. how can it be done..

I have tried

$scope.users = data.users;
 $scope.usersTemp = [];
$scope.usersTemp.push($scope.users );

and
 $scope.usersTemp = $scope.usersTemp

Have you tried with angular.copy ? Something like :

$scope.usersTemp = angular.copy($scope.usersTemp)

https://docs.angularjs.org/api/ng/function/angular.copy

您可以使用:

angular.copy ( myObjorArrayetc )

what you are trying to do seems to be creating a shallow copy of a JS array. If this is not your use case, please let me know.

There are several ways to do this in JS

const copy = [...original]; // es6 only, uses Symbol.iterator
const copy = original.slice(); // slices the array from index 0,      
                               // returning a shallow copy

const copy = Array.from(original, val => val); // es6 only, takes an 
// array-like object with .length property and a map function
const copy = original.map(x => x); 
// call to Array.prototype.map with identity function.

With those you can have :

const a = [1, 2];
const b = // shallow copy with one of the methods
a.push(3); // and b is still [1, 2]

A quick note regarding the other answers : a rapid look at the angular docs here seems to indicate that angular.copy returns a deep copy .

It is really important to grasp the difference : a shallow copy will merely create a new object and put all the values inside it, whereas a deep copy will try to make a copy of each of those values. What it means is that as objects in JS are mutable, if you create a shallow copy, you still share all of its values with the other copies. This is not the case with a deep copy.

eg :

const a1 = [{a: {b: 3}}];
const a2 = // shallow copy
(a1 === 2) // false
a1[0].a.b = 4 // reassign a prop of a value contained inside a1
(a1[0].a.b === 4) // true 

If a deep copy had been made, a new object would have been made.

Conclusion : use what you need depending of your use case. A shallow copy is quick to be made, but is subject to unwanted mutations, a deep copy is much more expensive to create but immune to mutations caused by share access. As a side note, there of course an impact on GC of these two approach (meaning a shallow copy will not release the references to values contained in the original ).

You can use

var copy = angular.copy(object);

It will make a exact replica of the object.

When using assignment operation in case of array both copy and orginal object bind the changes. So use angular.copy(oldArray, newArray) .

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