DekGenius.com
[ Team LiB ] Previous Section Next Section

Recipe 6.5 Inserting Elements in the Middle of an Array

6.5.1 Problem

You want to insert elements in the middle of an array.

6.5.2 Solution

Use the splice( ) method.

6.5.3 Discussion

You can use the splice( ) method to insert elements as well as delete them. Any values passed as parameters to the splice( ) method following the first and second parameters are inserted into the array starting at the index specified by the start parameter. All existing elements following that index are shifted to accommodate for the inserted values. If 0 is passed to the splice( ) method for the deleteCount parameter, no elements are deleted, but the new values are inserted:

myArray = ["a" ,"b", "c", "d"];

// Insert three string values--"one", "two", and "three"--starting at index 1.
myArray.splice(1, 0, "one", "two", "three");

// myArray now contains seven elements: "a", "one", "two", "three", "b", "c", and
// "d".
for (var i = 0; i < myArray.length; i++) {
  trace(myArray[i]);
}

You can also delete elements and insert new elements at the same time:

myArray = ["a" ,"b", "c", "d"];

// Remove two elements and insert three more into myArray starting at index 1.
myArray.splice(1, 2, "one", "two", "three");

// myArray now contains five elements: "a", "one", "two", "three", and "d".
for (var i = 0; i < myArray.length; i++) {
  trace(myArray[i]);
}
    [ Team LiB ] Previous Section Next Section