HTML and CSS Reference
In-Depth Information
}
/**
* Removes a pet from the array
*/
this.removePet = function(index){
/**
* Splice can remove items from an array. It accepts a start index
* and number of items
*/
_pets.splice(index, 1);
}
/**
* Sets the pet array
*/
this.setPets = function(pets){
/**
* Clear the pets array, using Array.length = 0 will remove
* every element in the array as apposed to creating a new array
* using _pets = [];
*/
_pets.length = 0;
/**
* Instead of completely replacing the pets array with the new array,
* each pet should go through the same validation in the addPet method.
* Instead of duplicating any validation code, it makes sense to just
* call the addPet method for every pet using a for loop.
*/
for(var i = 0; i < pets.length; i++){
_self.addPet(pets[i]);
}
}
/**
* Gets the pet array
*/
this.getPets = function(){
return _pets;
}
}
As you can see from the preceding code, most of the methods are fairly self-
explanatory, except for the setPets method. From the setPets code, you can
see that you have to first clear the pets array using _pets.length = 0 . This is
slower than assigning a new empty array to the _pets variable using _pets = [] ;
however, it will simply remove all of the array elements rather than create a new
 
Search WWH ::




Custom Search