有什么方便的方法可以替换数组的内容并对其进行引用?我不想这样替换数组:
var arr1 = [1,2,3]; var referenceToArr1 = arr1; var arr2 = [4,5,6]; arr1 = arr2; // logs: [4,5,6] false console.log(arr1, arr1===referenceToArr1); // logs [1,2,3] console.log(referenceToArr1);
这种方法arr1具有的内容arr2,但是我松了其中的引用referenceToArr1,因为它仍然指向 原始内容 arr1。
arr1
arr2
referenceToArr1
这样,我就不会失去参考:
var arr1 = [1,2,3]; var referenceToArr1 = arr1; var arr2 = [4,5,6]; arr1.length = 0; for (var i = 0; i < arr2.length; i++) { arr1.push(arr2[i]); } // logs: [4,5,6] true console.log(arr1, arr1===referenceToArr1); // logs: [4,5,6] console.log(referenceToArr1)
这里的缺点是,我必须清空arr1.length = 0,迭代其中的每个元素arr2并arr1用手将其推入。
arr1.length = 0
我的问题是:
背景:
我有一个带有服务的AngularJS应用。在此服务内部,我有一个数组来保持从服务器加载的所有元素。来自服务的数据get绑定到控制器,并在视图中使用。当服务中的数据发生更改(例如发生重新提取)时,我想自动更新控制器变量和绑定到的视图。
这是一个柱塞: http ://plnkr.co/edit/8yYahwDO6pAuwl6lcpAS?p=preview
var app = angular.module('plunker', []); app.controller('MainCtrl', function($scope, myService) { $scope.name = 'World'; myService.fetchData().then(function(data) { console.log(data) $scope.data = data; }) }); app.service('myService', function($timeout, $q) { var arr; var deferred; var loadData = function() { // here comes some data from the server var serverData = [1,2,3]; arr = serverData; deferred.resolve(arr); // simulate a refetch of the data $timeout(function() { var newServerData = [4,5,6]; // this won't work, because MainCtrl looses it's reference // arr = newServerData; }, 1000); $timeout(function() { var newServerData = [7,8,9]; arr.length = 0; [].push.apply(arr, newServerData); }, 2000); $timeout(function() { var newServerData = [10,11,12]; [].splice.apply(arr, [0, arr.length].concat(newServerData)); }, 3000); } return { fetchData: function() { deferred = $q.defer(); loadData(); return deferred.promise; } } })
和视图:
<!DOCTYPE html> <html ng-app="plunker"> <head> <meta charset="utf-8" /> <title>AngularJS Plunker</title> <script>document.write('<base href="' + document.location + '" />');</script> <link rel="stylesheet" href="style.css" /> <script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.16/angular.js" data-semver="1.2.16"></script> <script src="app.js"></script> </head> <body ng-controller="MainCtrl"> <ul> <li ng-repeat="d in data">{{d}}</li> </ul> 3 refetches every second </body> </html>
那这个呢:
// 1. reset the array while keeping its reference arr1.length = 0; // 2. fill the first array with items from the second [].push.apply(arr1, arr2);