Page 117 - JavaScript
P. 117
arr = ["big data"];
var i = 100;
while (i > 0) {
addListener(arr); // the array is passed to the function
arr = []; // only removes the reference, the original array remains
array.push("some large data"); // more memory allocated
i--;
}
// there are now 100 arrays closed over, each referencing a different array
// no a single item has been deleted
To prevent the risk of a memory leak use the one of the following 2 methods to empty the array in
the above example's while loop.
Method 2
Setting the length property deletes all array element from the new array length to the old array
length. It is the most efficient way to remove and dereference all items in the array. Keeps the
reference to the original array
arr.length = 0;
Method 3
Similar to method 2 but returns a new array containing the removed items. If you do not need the
items this method is inefficient as the new array is still created only to be immediately
dereferenced.
arr.splice(0); // should not use if you don't want the removed items
// only use this method if you do the following
var keepArr = arr.splice(0); // empties the array and creates a new array containing the
// removed items
Related question.
Using map to reformat objects in an array
Array.prototype.map(): Returns a new array with the results of calling a provided function on every
element in the original array.
The following code example takes an array of persons and creates a new array containing
persons with a 'fullName' property
var personsArray = [
{
id: 1,
firstName: "Malcom",
lastName: "Reynolds"
}, {
id: 2,
https://riptutorial.com/ 74

