Skip to content

Instantly share code, notes, and snippets.

@cameronism
Created March 24, 2011 19:09
Show Gist options
  • Save cameronism/885646 to your computer and use it in GitHub Desktop.
Save cameronism/885646 to your computer and use it in GitHub Desktop.
Add one or more elements at the specified index and returns the new length of the array.
// Syntax
// ------
// array.insertAt(index, element1, ..., elementN)
// Parameters
// ------
// index
// : Index at which to insert elements. If negative, will begin that many elements from the end.
// element1, ..., elementN
// : The elements to add to the array.
Array.prototype.insertAt = function (index) {
var my = this,
args = my.slice.call(arguments, 1);
if (!index) {
return my.unshift.apply(my, args);
}
if (index >= my.length) {
return my.push.apply(my, args);
}
my.splice.apply(my, [index, 0].concat(args));
return my.length;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment