array.concat vs angular.copy

时间:2014-09-08 03:32:05

标签: javascript angularjs

我注意到[].concat()angular.copy()的数组表现相似。例如,

var x = [5, 2];
var y = [].concat(x);
// y = [5, 2]

x = [2, 3];
// y = [5, 2]

var z = angular.copy(x);
// z = [2, 3];

x = [6, 9];
// z = [2, 3];

[].concat()angular.copy(src,[dest])之间是否存在差异?

2 个答案:

答案 0 :(得分:2)

angular.copy执行源的深层复制并将其放在目标上(源和目标及其内容的数组,甚至是引用类型,都指向不同的引用位置)。但是当你执行[] .concat(源和目标数组都指向不同引用时,其引用类型内容指向相同引用),它只返回一个新数组,所以只考虑在你的例子中同时使用angular.copy[].concact是因为它将数组对象的新引用分配给lhs变量。 / p>

但请考虑具有对象数组的情况。

  $scope.arr = [{name:'name1'}, {name:'name2'}, {name:'name3'}, {name:'name4'}];
  $scope.arrConcat = [].concat($scope.arr); //Get a new array
  $scope.arrCopy = angular.copy($scope.arr); //Get a new copy

 //Now change the name property of one of the item

  $scope.arr[3].name="Test";

 //Now see who all have been changed

 console.log($scope.arr[3].name); //Of course will output "Test"

 console.log($scope.arrConcat[3].name); //Will also output "Test" because the new array items still holds the same reference of the objects.

 console.log($scope.arrCopy[3].name); //Will output name4 because this contains another reference which holds the copy of the value of the object at index 3 from source array



//Push something on to the original array 
  $scope.arr.push({name:'name5'});

  //You will see that new item is not available here, which is exactly the behaviour that you are seeing in your case because both the arrConcat and arrCopy holds its own version of array through the items in arrConcat and arr are from the same reference.
  console.log($scope.arrConcat);
  console.log($scope.arrCopy);

所以唯一的事情就是在你的情况下[].concat是一种方便的方法来获取源数组的副本,因为你的数组只有原语,所以没有问题。

<强> Example - Demo

答案 1 :(得分:0)

http://plnkr.co/edit/06zLM8g34IDBLUmPtwV2?p=preview

var x = [5, 2];
var y = [].concat(x);
// y = [5, 2]


var x = [5, [5, 2]];
var y = [].concat(x);
// y = [5, 2]

检查一下,[]。copy()永远不会像angular.copy()

那样进行深度复制