Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to empty an array?

I read the topic How do I empty an array in JavaScript?

Answer :

Very simple:

A = [];

I am interested in the comment by Daniel Baulig:

this will NOT empty the array, but create a new, empty array. This might cause problems, especially if there are other references to the array. OP: Please consider to accept Matthew's answer instead. It is the cleaner and formally correct approach. – Daniel Baulig Jan 19 '11 at 13:08

Can you tell me what problems this could cause?

like image 310
Michael Phelps Avatar asked Apr 11 '26 12:04

Michael Phelps


1 Answers

The problem is that you may have another reference to that array.

Consider this :

var A = ['A'];
var B = A;

If you do

A = [];

this will still let B be ['A']. That's the difference between emptying (or changing) an array, or replacing it (what you did).

When you do

A.length=0;

then B will be empty too.

like image 173
Denys Séguret Avatar answered Apr 13 '26 01:04

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!