Javascript ArrayList
In many Javascript projects I've felt the need to use an ArrayList (like in Java or other languages). However the Javascript Array Object lacks a few convenience methods:
Array.prototype.remove = function(el){
var index = this.indexOf(el);
if(index != -1) {
this.splice(index, 1);
}
}
Array.prototype.add = function(el){
if(this.indexOf(el) == -1){
this.push(el);
}
}
Array.prototype.contains = function(el){
return this.indexOf(el) != -1;
}
Array.prototype.toggle = function(el){
if(this.indexOf(el) == -1){
this.add(el);
} else this.remove(el);
}
Hope this is as useful for someone as it has been for me.
Written by Filipe Leandro
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#