Recipe 5.5.
Inserting Elements in the Middle of an Array
Problem
You
want to insert elements in
the middle of an array.
Solution
Use the splice( ) method.
Discussion
You can use the splice( ) method to
insert elements as well as delete them. Values passed to the
splice( ) method after the first and second parameters are
inserted into the array at the index specified by the
start parameter; all existing elements following
that index are shifted up to accommodate 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:
var letters:Array = ["a", "b", "c", "d"];
// Insert three string values ("one", "two", and "three")
// starting at index 1.
letters.splice(1, 0, "r", "s", "t");
// letters now contains seven elements:
// "a", "r", "s", "t", "b", "c", and "d".
for (var i:int = 0; i < letters.length; i++) {
trace(letters[i]);
}
You can also delete elements and insert new
elements at the same time:
var letters:Array = ["a", "b", "c", "d"];
// Remove two elements and insert three more
// into letters starting at index 1.
letters.splice(1, 2, "r", "s", "t");
// myArray now contains five elements:
// "a", "r", "s", "t", and "d".
for (var i:int = 0; i < letters.length; i++) {
trace(letters[i]);
}
|