Array Power, Part III - DHTML Lab | 9
Array Power, Part III
With splice( ):
myArray = [0,"cat",true]; myOldPet = myArray.splice(1,1,"dog");
Without splice( ):
|Statement used||myArray becomes|
|1.||myArray = [0,"cat",true];||[0,"cat",true]|
|2.||ind = 1;|
|3.||cnt = 1;|
|4.||insertArray = ["dog"];|
|5.||removedElements = myArray.slice(ind,ind+cnt);||[0,"cat",true]|
|6.||endArray = myArray.slice(ind+cnt);||[0,"cat",true]|
|7.||myArray.length = ind;|||
myArray[myArray.length] = insertArray[i];
myArray[myArray.length] = endArray[i];
|10.||myOldPet = removedElements;|
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, removedElements, using slice() to store the removed elements.
6. a third array is created, endArray, again using slice() to store the elements after the elements we will remove.
7. 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:
- myArray, our original array, that now contains only the elements up to the position where elements were to be removed.
- insertArray, the array of elements to insert.
- endArray, the elements from myArray that were positioned after the insertion point.
8. the elements of insertArray are appended to myArray.
9. the elements of endArray are appended to myArray.
8. the removed element, in removedElements, is assigned to the myOldPet variable.
We should now be familiar with the statements necessary to replicate the splice() method behaviour for browsers that do not have it built-in. We can, therefore, move on to prototype this method for these browsers.
Produced by Peter Belesis andAll Rights Reserved. Legal Notices.
Created: May 16, 2000
Revised: May 16, 2000