Difference between create a new Array and clear the length
本问题已经有最佳答案,请猛点这里访问。
如果我必须删除数组中的所有项,那么使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | function MyCtrl($scope) { $scope.arrayData = ["1","2","3"]; $scope.newArray1 = function(){ $scope.arrayData = new Array(); } $scope.newArray2 = function(){ $scope.arrayData = []; } $scope.lengthZero = function(){ $scope.arrayData.length = 0; } $scope.populate = function(){ $scope.arrayData.push("1","2","3"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"> Data: <ul> <li ng-repeat="data in arrayData">{{data}} </li> </ul> <button ng-click="newArray1()">New Array - 1st method</button> <button ng-click="newArray2()">New Array - 2nd method</button> <button ng-click="lengthZero()">Length = 0</button> <button ng-click="populate()">Populate</button> |
仅仅使用
如果使用
使用
清除数组并保留引用的更好方法是:
1 2 3 4 5 | var array = [1,2,3,4,5]; while (array.length) { array.pop(); } |
还要看一看这个完全相同的问题:array.length=0和array=[]之间的差异?