JavaScript's two methods for clearing array elements are simple to compare

  • 2020-07-21 06:56:43
  • OfStack

This article illustrates a simple comparison of two JavaScript methods for clearing array elements. Share to everybody for everybody reference. The specific analysis is as follows:

There are several ways to empty arrays in JavaScript:


var arr = [1, 2, 3]; 
arr = [];// methods 1
arr.length = 0;// methods 2
arr = null;// methods 3
delete arr;// methods 4

Here is a comparison of the most commonly used types 1 and 2


var arr = [1, 2, 3];
//  methods 1
//  Advantage: If an array is used elsewhere arr This method is relatively safe. It's also easy and fast 
//  Cons: Added extra memory overhead, rebooted 1 A new empty array 
arr = [];
//  methods 2
//  Pros: If used otherwise arr Element where you want to synchronize your observations arr The element is emptied, so this is a good choice 
//  Disadvantages: Set the array length Property causes the array to be deleted index for length And the elements after that, which is very expensive in terms of performance 
//  This method is also 4 The worst performance of the two methods. 
arr.length = 0;

I hope this article has been helpful for your javascript programming.


Related articles: