I have created an utility function which I include in almost all Javascript code I write. The purpose of the said function is to simply remove one element from an array. It takes an array and an index as the arguments, and returns the array which has the required element removed.
Here’s the function:
sliceHere = function(array, i)
{
buffOne = array.slice(0, i);
buffTwo = array.slice(i + 1);
return buffOne.concat(buffTwo);
}
It works quite alright. If I had an array a = ["a", "b", "c"], and I wanted to remove the "a" from it, I’d simply do a = sliceHere(a, 0);.
Although this did work, I wanted to replace it with something more “elegant”. What I wanted to do is to make the function sliceHere a method of all the arrays I have. So I could simply do a.sliceHere(0) and achieve the same effect. It just feels like a better way of doing things, correct me if I’m wrong.
What I did was this:
sliceHere = function(i)
{
buffOne = this.slice(0, i);
buffTwo = this.slice(i + 1);
this = buffOne.concat(buffTwo);
}
Array.prototype.sliceHere = sliceHere
This didn’t seem like it would work at all. Because I knew that “this” probably wasn’t the actual array. How do I reference the array from inside of a method?
Why do you want to re-invent the wheel?
Array.prototype.splicealready does the same thing:Okay, let’s re-invent the wheel:
With splice:
Without splice:
If you do not want the method to show up in
for(.. in ..)loops, useObject.defineProperty(Array.prototype, 'sliceHere', {value: /*function here*/});.