Code Snippet
Empty an Array
This is one of the fastest and easiest ways of emptying an array. Of course there are may other ways, but those usually include creation of a new array. This way you reuse the same array.
var myArray = ["one", "two", "three"];
// console.log( myArray ) => ["one", "two", "three"]
myArray.length = 0;
// console.log( myArray ) => []
isnt:
myArray = [];
just as good?
I bet this:
myArray.length = 0;does not work in all browsers where the snippet provided above – does.
Excellent code, myArray.empty() works as well.
it’s not a standard prototype on the Array constructor.
Atleast not in the latest WebKit browsers.
Ha, just do:
arrayobj.splice(0,arrayobj.length).You can even add that to a prototype as
Array.prototype.empty() {this.splice(0,this.length);}
and you are done.
I think:
myArray = [];
/* or */
myArray = new Array();
Would be the best, since it’s cross-browser stuff.
The problem with myArray = [] and myArray = new Array() is that technically you are not emptying the array, but instead you are creating a new array. Creating new arrays is a bit of work for browsers, so simply setting the array’s length to 0 is probably best.
none of the examples works
Out of the above I’ve only tested emptying an array through splicing and it did work perfectly.
Here’s a jsPerf test case: http://jsperf.com/emptying-arrays
DigWP
A book and blog co-authored by Jeff Starr and myself about the World's most popular publishing platform.
Quotes on Design
Design, like Art, can be an elusive word to define and an awfully fun thing to have opinions about.
HTML-Ipsum
One-click copy to clipboard access to Lorem Ipsum text that comes wrapped in a variety of HTML.
Bookshelf
Hey Chris, what books do you recommend? These, young fertile mind, these.