Computers start counting from zero. So 0 is 1, 1 is 2, and so on. That’s why list[2]
selects item 3
from the array
Code for the array in the example:
var list = ['item 1', 'item 2', 'item 3', 'item 4']
splice()
needs two things to work:
- A number to specify which position you want to delete from.
- A number to specify how many items we want to delete, from that position.
So list.splice(2, 1)
targets the 3th item in the array, and deletes that single item.
If you instead wrote: list.splice(2, 2)
then it would delete both the 3th and the 4th item in the array.
The second number in splice()
specifies how many elements we want to delete, from the position we target. If we had 10 items in an array and wrote list.splice(3, 5)
then it would delete 5 items from the 4th position in the array.