splice

Basic Usage

1st param – what index of the array to start
2nd param – how many elements to remove

in firebug console, we first see what test is. Which gives us the result of the full array. Then we do test.splice(1,2), which means at index 1, we remove 2 elements. This returns us “two” and “three”, meaning we removed “two” and “three.

Then we see the results of test again to ensure that “two” and “three” are removed from the original array.

> test
Array [ “one”, “two”, “three”, “four”, “five”, “six” ]
> test.splice(1,2)
Array [ “two”, “three” ]
> test
Array [ “one”, “four”, “five”, “six” ]

in firebug console, we start at index 2, which would be “ten”.
We remove 2 elements, which would be the “ten”, and “six”. The removed elements are returned.
We then add the word “nine”.

> test
Array [ “one”, “four”, “ten”, “six” ]
> test.splice(2,2,”nine”)
Array [ “ten”, “six” ]
> test
Array [ “one”, “four”, “nine” ]

Using splice in List implmentation

We first make a List class default constructor. we initialize member variables. Then we assign function definitions append, remove, length, insert, clear, and toString.

delete the array of elements. then reassign to empty array.

We loop through all the elements of our dataStore array, and if the elements match, we simply return the index.

We first get the index of where we want to remove the element.
Then when we have the index, we use the index as parameter for the splice index to know where to start. The 1 at the 2nd parameter of the splice, means to remove 1 element at that index.

We insert at given position pos, removing 0 elements, and insert the element to be inserted.