Tech Junkie Blog: JavaScript Methods: Array.splice() Method

Monday, May 7, 2018

JavaScript Methods: Array.splice() Method

The JavaScript array splice() method allows you to delete and insert array elements in one method
Before we get to the examples let's see how we would use the splice() method on an array first.

The splice method takes 1....n method parameters.  The first parameter specify the position of the array that will be deleted.  The second parameter specify the number of elements to be deleted after the first element's index position, or splice out.  Any subsequent parameters will be the elements that will be added to the array.  If there's only one parameter then all the elements before the first parameter's position will be deleted

For example let say we have the following array

    <script>
        var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9,10];
    </script>

In this example we deleted everything that is before the array index 2 by typing numbers.splice(2).  As you can since we only have 1 parameter passed in the elements after the index 2 is spliced out and the numbers array is changed to have just two elements 1,2.  The splice() method changes the original array.













So now let's add a second parameter to the splice method, let's say we want to start at the index 2, and splice out the next the next three elements we would do the following numbers.splice(2,3) .  So the expected result is the three elements after index 2 will be removed from the array









As you can see the next three elements after the index 2 is splice out of the array so the output is 3,4,5

In the last example we remove the next three element after the index 2 again and then add the numbers 60,70 into the array after the splice.

numbers.splice(2,3,60,70)


No comments:

Post a Comment