Out of Hanwell

September 21, 2005

JavaScript Arrays the Long Way Around

Filed under: Uncategorized — Matthias Miller @ 6:41 am

There’s an Indian proverb that says there are two ways to touch one’s nose: you can touch it directly or you can touch it the long way around.

I was searching the Internet for JavaScript array extensions when I found this function:

Array.prototype.insertAt = function (what, iIndex)
{
if (iIndex < this.length) {
var aAfter = this.splice(iIndex, 100000, what);
for (var i = 0; i < aAfter.length; i++) {
this.push(aAfter[i]);
}
} else {
this.push(what);
}
}

What’s so odd about this?

You can do it in a single function call:

myArray.splice(index, 0, element);

Updated post not to point fingers; slice is simply a weird function.

1 Comment »

  1. The universe is change; our life is what our thoughts make it.

    Comment by Vick — November 19, 2009 @ 11:48 pm


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.