簡體   English   中英

array.concat與angular.copy

[英]array.concat vs angular.copy

我注意到[].concat() angular.copy()與數組的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])之間有關鍵區別嗎?

angular.copy執行源的深層復制並將其放置在目標上( source和dest的數組及其內容,甚至引用類型,都指向不同的引用位置 )。 但是,當您執行[] .concat( source和dest的數組都指向不同的引用,而其引用類型的內容都指向相同的引用 )時,它只是返回一個新數組,因此僅認為在使用angular.copy這是相似的angular.copy在您的示例中, angular.copy[].concact是將數組對象的新引用分配給lhs變量。

但是考慮一下您擁有對象數組的情況。

  $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是一種獲取源數組副本的便捷方法,因為您的數組僅具有基元,因此沒有問題。

示例-演示

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()那樣進行深層復制

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM