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

Array Power, Part III - DHTML Lab | 9

Logo

Array Power, Part III
spliceless replacement


Replacing Elements

With splice( ):

myArray = [0,"cat",true];
myOldPet = myArray.splice(1,1,"dog");

Without splice( ):

Statement usedmyArray 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;[0]
8.for(i=0;i<insertArray.length;i++){
    myArray[myArray.length] = insertArray[i];
}
[0,"dog"]
9.for(i=0;i<endArray.length;i++){
    myArray[myArray.length] = endArray[i];
}
[0,"dog",true]
10.myOldPet = removedElements[0]; 

Step-by-Step



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:

  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.

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 and

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

URL: https://www.webreference.com/dhtml/column33/5.html