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

Array Power, Part III - DHTML Lab | 7

Logo

Array Power, Part III
spliceless removing


Let's do the examples from the previous page again, this time without splice(). A "spliceless" browser would have to execute many more statements to achieve the same functionality.

Removing Elements

With splice( ):

myArray = [0,"cat",true];
removedElements = myArray.splice(1,1);
myPet = removedElements[0];

Without splice( ):

Statement usedmyArray becomes
1.myArray = [0,"cat",true];[0,"cat",true]
2.ind = 1; 
3.cnt = 1; 
4.removedElements = myArray.slice(ind,ind+cnt);[0,"cat",true]
5.endArray = myArray.slice(ind+cnt);[0,"cat",true]
6.myArray.length = ind;[0]
7.for(i=0;i<endArray.length;i++){
    myArray[myArray.length] = endArray[i];
}
[0,true]
8.myPet = 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, removedElements, using the built-in slice() method. The slice() method, available in all browsers, extracts elements from an array, returning a new array of these elements, without changing the original array. We now have our array of removed elements.

5. another array is created, endArray, again using slice(). These elements are the ones after the elements we need to remove.

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. removedElements, the array of removed elements.
  3. endArray, the elements from myArray that were positioned after the elements that were removed.
We now have to rebuild the original array.

7. the elements of endArray are appended to myArray.

8. the first, and in this example the only, element of removedElements is assigned to the myPet variable.

Next, we'll do some spliceless insertion of elements.


Produced by Peter Belesis and

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

URL: http://www.webreference.com/dhtml/column33/3.html