JavaScript is a great language. There was a time when I was rather against it (mainly during the browser wars) but with modern libraries and the like, cross browser processing is exactly where it should be. However, there are a lot of times when you just need some simple processing done and most libraries – even their cores – are too bloated to be of any use. Below I’ve outlined three functions has(), indexOf() and remove() that extend the existing Array prototype to add some much needed features.
Array.prototype.indexOf = function(val) {
for(i = 0; i < this.length; i++) {
if(this[i] == val) {
return i;
}
}
return -1;
};
Array.prototype.has = function(val) {
return this.indexOf(val) > 0 ? true:false;
};
Array.prototype.remove = function(val) {
var x = this.indexOf(val), y = 0;
for(i = 0; i < this.length; i++) {
if(i != x) {
this[y]= this[i];
y++;
}
}
this.pop();
};indexOf()
Often times you have a string and you need to figure out where in the array it appears. Since JavaScript doesn’t technically support associative arrays (array object conversion does occur implicitly) you can either loop through the array every time, or just extend array!
Example for indexOf()
var myArray = ["an","array","with","a","bunch","of","words"];
document.Write(myArray.indexOf("a")); // returns 3
document.Write(myArray.indexOf("491")); // returns -1has()
Sometimes you just need to know if a value is present within an array. has() takes care of that returning a simple true:false boolean. Rather than re-inventing the wheel, it works in conjunction with indexOf()
Example for has()
var myArray = ["an","array","with","a","bunch","of","words"];
document.Write(myArray.has("with")); // returns true
document.Write(myArray.has("feet")); // returns falseremove()
Finally, sometimes removing a single element from an array is necessary.
Example for remove()
var myArray = ["an","array","with","a","bunch","of","words"];
myArray.remove("array"); // myArray now contains ["an","with","a","bunch","of","words"]Hopefully the functions are of help! If there are a lot of people confused over Prototypal Inheritance, maybe that would be an interesting topic.