javascript - array.concat 与 angular.copy

标签 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]) 之间有关键区别吗?

最佳答案

angular.copy 执行源的深层复制并将其放置在目标上(源和目标的数组及其内容,甚至引用类型,都指向不同引用位置)。但是,当您执行 [].concat 时(源数组和目标数组都指向不同引用,并且其引用类型内容指向相同引用),它只是返回一个新数组,因此在示例中仅认为与使用 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 是一种获取源数组副本的便捷方法,因为您的数组只有基元,所以没有问题。

<强> Example - Demo

关于javascript - array.concat 与 angular.copy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25717101/

相关文章:

javascript - 如何在包含 '#'键的javascript中获取JSON对象的属性

javascript - Galleria JS 无法在生产环境中使用 Rails 管道

Javascript:无法覆盖变量

javascript - npm 删除 package.json 中不再存在的所有包

javascript - 如何在 Angularjs 中将文件 json 导出为 CSV 或 XLSX 格式

AngularJS SEO 元和描述标签

angularjs - 在 angularjs 中使用 $compile

javascript - AngularJS 破坏了 JQuery 动画

javascript - 缩小时的 Angular 注入(inject)

javascript - 为什么算法性能不同