If I have to delete all the items in an array, what's the difference between using new Array
and length = 0
? In the example, apparently the result looks the same.
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");
}
}
Data:
- {{data}}
Answer
There is quite a big difference between just using []
and .length = 0
.
If you use = []
you will assign a new reference to the variable, losing your reference to the original. By using .length = 0
you will clear the original array, leaving the original reference intact.
No comments:
Post a Comment