Tuesday, April 23, 2019

javascript - Difference between create a new Array and clear the length




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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...