Ways to clear the array in javascript (not all)

Method 1: Set the length of the array to 0;

const arr = [ 1, 2, 3, 4, 5 ];
arr.length = 0;

Consequence: This method will not change the original array reference. This means that if you use the assignment operator (=) to assign an array reference to another array reference, applying this method on one array will also clear the other array reference. 

Method 2: Assign a reference to the new array;

let arr = [ 1, 2, 3, 4, 5 ];
arr = [];

Example:

let hisArray = [ 'Some', 'thing' ];

let herArray = [ 'blog', 'dot', 'green', 'roots', 'dot', 'info', ' ', 
                    'blog', 'dot', 'green', 'roots', 'dot', 'info', ' ',
                    'blog', 'dot', 'green', 'roots', 'dot', 'info', ' ',
                    'blog', 'dot', 'green', 'roots', 'dot', 'info', ' ',
                    'blog', 'dot', 'green', 'roots', 'dot', 'info', ' ',
                    'blog', 'dot', 'green', 'roots', 'dot', 'info', ' ',
                    'blog', 'dot', 'green', 'roots', 'dot', 'info', ' ',
                    'blog', 'dot', 'green', 'roots', 'dot', 'info', ' ',
                    'blog', 'dot', 'green', 'roots', 'dot', 'info', ' ',
                    'blog', 'dot', 'green', 'roots', 'dot', 'info', ' ',
                    'blog', 'dot', 'green', 'roots', 'dot', 'info', ' ',
                    'blog', 'dot', 'green', 'roots', 'dot', 'info'
                ];

herArray = hisArray;

console.time('Approach  2: new assignment');
hisArray = [];
console.timeEnd('Approach  2: new assignment');

console.group('Approach  2: Empty array by assigning a new empty Array []')
console.log('hisArray =>', hisArray);
console.log('herArray =>', herArray);
console.groupEnd();

 Output:

Approach  2: new assignment: 0.005ms
Approach  2: Empty array by assigning a new empty Array []
  hisArray => []
  herArray => [ 'Some', 'thing' ]

Consequence: The original array hisArrayhas been changed, but the other values ​​of the array herArrayremain unchanged.

Method 3: Use pop() until the end 

let someArray = [ 'blog', 'dot', 'green', 'roots', 'dot', 'info'];

console.time('Approach  3: pop()');
while(someArray.length > 0) {
    someArray.pop();
}
console.timeEnd('Approach  3: pop()');

console.group('Approach  3: Use pop until death');
console.log('someArray => ', someArray);
console.groupEnd();

Consequence: As the number of elements in the array increases, this approach will make things very slow. So don't use this method when dealing with large data.

Guess you like

Origin blog.csdn.net/baidu_39043816/article/details/108575700