Array Power, Part III - DHTML Lab | 8 | WebReference

Array Power, Part III - DHTML Lab | 8


Array Power, Part III
spliceless insertion

Inserting Elements

With splice( ):

myArray = [0,"cat",true];

Without splice( ):

Statement usedmyArray becomes
1.myArray = [0,"cat",true];[0,"cat",true]
2.ind = 2; 
3.cnt = 0; 
4.insertArray = ["dog","mouse"]; 
5.endArray = myArray.slice(ind+cnt);[0,"cat",true]
6.myArray.length = ind;[0,"cat"]
    myArray[myArray.length] = insertArray[i];
    myArray[myArray.length] = endArray[i];


1. myArray is declared.

2. ind is declared to store the position at which we will begin to change myArray.

3. cnt is declared to store the number of elements to remove.

4. a new array is created, insertArray, to store the elements we want to insert into myArray.

5. another array is created, endArray, using slice(). These elements are the ones after the insertion point.

6. myArray, which has yet to be changed, is now truncated, by changing its length property to the value of ind. We now have three arrays:

  1. myArray, our original array, that now contains only the elements up to the position where elements were to be removed.
  2. insertArray, the array of elements to insert.
  3. endArray, the elements from myArray that were positioned after the insertion point.
We now have to rebuild the original array.

7. the elements of insertArray are appended to myArray.

8. the elements of endArray are appended to myArray.

Finally, some spliceless insertion and removal of elements.

Produced by Peter Belesis and

All Rights Reserved. Legal Notices.
Created: May 16, 2000
Revised: May 16, 2000