刪除所有元素

var arr = [1, 2, 3, 4];

方法 1

建立一個新陣列並使用新陣列覆蓋現有陣列引用。

arr = [];

必須小心,因為這不會從原始陣列中刪除任何專案。傳遞給函式時,陣列可能已被關閉。雖然你可能沒有意識到這一點,但陣列將在函式的生命週期內保留在記憶體中。這是記憶體洩漏的常見原因。

陣列清除錯誤導致記憶體洩漏的示例:

var count = 0;

function addListener(arr) { // arr is closed over
  var b = document.body.querySelector("#foo" + (count++));
  b.addEventListener("click", function(e) { // this functions reference keeps
    // the closure current while the
    // event is active
    // do something but does not need arr       
  });
}

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

為防止記憶體洩漏的風險,請使用以下兩種方法之一清空上述示例的 while 迴圈中的陣列。

方法 2

設定 length 屬性會將所有陣列元素從新陣列長度刪除到舊陣列長度。這是刪除和取消引用陣列中所有專案的最有效方法。保留對原始陣列的引用

arr.length = 0;

方法 3

與方法 2 類似,但返回包含已刪除項的新陣列。如果你不需要這些項,則此方法效率低,因為仍會建立新陣列以立即取消引用。

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

相關問題