Array.splice() (Method)

An array editing tool.

Availability:

ECMAScript edition - 3
JavaScript - 1.2
JScript - 5.5
Internet Explorer - 5.5
Netscape - 4.0
Netscape Enterprise Server - 3.0
Property/method value type:Array object
JavaScript syntax:-myArray.splice(startPos, aCount, newElements)
Argument list:aCountAn optional count of items to remove
newElementsAn optional list of items to add
startPosAn entry at which to start splicing

The start position indicates where the splicing is to occur. If there are no other arguments, then the remainder of the array is truncated.

If there is a count argument present, only that number of items will be removed and the subsequent ones shuffled up to be adjacent to the front section of the array.

Any additional arguments are taken to be values to be inserted. They are not evaluated according to the techniques used by the Array.concat() method. If arrays are specified, they will not be flattened but will be inserted as they are.

This method operates on the array in place, therefore it modifies the original receiving array.

Specifying a count value of zero provides the functionality of an insert() method.

Specifying a count value larger than the array length does not cause an error, but instead truncates the array which behaves like a replace() method.

The method call returns an array containing the elements that were removed. This provides an alternative to the slice() method, but you should use slice() for portability since some MSIE browsers do not support the splice() method.

Warnings:

Example code:

   // Create an array and test the Array.splice() method
   myArray = new Array("AAA", "BBB", "CCC", "DDD", "EEE");
   document.write("Array<BR>")
   displayArrayAsTable(myArray);
   document.write("Array.splice() result<BR>")
   displayArrayAsTable(myArray.splice(3, 1, "XXX", "YYY", "ZZZ"));
   document.write("Array after splice<BR>")
   displayArrayAsTable(myArray);
   
   // Display an array in a table
   function displayArrayAsTable(anArray)
   {
      myLength = anArray.length;
      document.write("<TABLE BORDER=1>");
      for(myIndex = 0; myIndex < myLength; myIndex++)
      {
         document.write("<TR><TD>");
         document.write(myIndex);
         document.write("</TD><TD>");
         document.write(anArray[myIndex]);
         document.write("</TD></TR>");
      }
      document.write("</TABLE><BR><BR>")
   }

See also:Array.prototype

insert figure 0107

Cross-references:

ECMA 262 edition 3 - section - 15.4.4.12