Welcome to the forums.
At this point, it isn’t really important to understand exactly how the
Array.splice() method works, but since you asked, I’ll try to explain.
First of all,
This method takes one required argument, and can also take additional optional arguments. Arguments are the values separated by commas between the
( ). The first argument in the example is
1. That is the index where we wish to make a change to the array (referred to as list in the exercise). The second argument is
0. This is the number of array elements that we want to remove. Since we don’t want to remove any, the value is
0. The third argument is
'mango' will be added to the array at index 1. If we change these values, we can change the array differently.
[ ‘apple’, ‘mango’, ‘banana’, ‘pear’ ]
If I wanted to delete a couple of the original elements, and add new ones, I could do this:
const myList = ['apple', 'banana', 'pear']; myList.splice(1, 2, 'mango', 'plum') //starts at index 1, deletes 2 elements, adds mango & plum console.log(myList);
[ ‘apple’, ‘mango’, ‘plum’ ]
We could also remove only one element, and add several if we wish:
const myList = ['apple', 'banana', 'pear']; myList.splice(1, 1, 'mango', 'plum', 'orange', 'grape', 'cherry') //starts at index 1, deletes 1 element, adds mango, plum, orange, grape & cherry console.log(myList);
[ ‘apple’, ‘mango’, ‘plum’, ‘orange’, ‘grape’, ‘cherry’, ‘pear’ ]
'pear' was shifted to the end of the array. We started at index
1, deleted 1 element, and inserted 5 new elements.