July 2003
Intermediate to advanced
896 pages
45h 43m
English
You want to insert elements in the middle of an array.
Use the splice( )
method.
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 intomyArraystarting at index 1. myArray.splice(1, 2, "one", "two", "three"); //myArraynow contains five elements: "a", "one", "two", "three", and "d". for (var i = 0; i < myArray.length; i++) { trace(myArray[i]); }
Read now
Unlock full access