Why doesn't this remove "koi" and "eel" (the 2 positions that follow)
Why would it? Look at the array indexes and the values at these positions:
fish[0] "piranha"
fish[1] "barracuda"
fish[2] "koi"
fish[3] "eel"
fish.splice(1, 2)
says (as you yourself wrote) that starting with position 1 it should remove 2 elements.
So, at position 1 we have barracuda
, which gets removed. But you said to remove 2 elements, not 1, so it removes another one: At position 1 we now have koi
, which gets removed as well.
End result is that barracude
and koi
got removed, and we are left with ["piranha", "eel"]
as expected.
You could imagine the way splice
works like this:
// Define `remove` and `insert` primitives.
// Yes I know I'm now explaining `splice` with `splice`... but just think about
// those as basic ways to remove (and return) or insert one element at a given
// position.
const remove = (array, index) => array.splice(index, 1)
const insert = (array, index, el) => array.splice(index, 0, el)
// Our own implementation of `splice`, using only the remove/insert primitives.
// I'm adding the array itself as an additional parameter at the front.
function ourSplice (array, position, removeCount = null, ...newElements) {
// Note: This does not simulate the behavior of splice(), splice(undefined),
// splice(undefined, undefined) and similar things, which don't behave all the
// same. It assumes at least a valid position.
// Negative position means N elements from the *end* of the array.
if (position < 0) position += array.length
// Unspecified remove count means to remove all elements starting with the given
// position (note that in the real splice function, this works only if the
// argument is omitted, not when it is undefined or null)
if (removeCount === null) removeCount = array.length - position
// Remove the given number of elements starting at the given position
const removed = []
for (let i = 0; i < removeCount; i++) {
removed.push(remove(array, position))
}
// Add any new elements given at the given position
for (let i = 0; i < newElements.length; i++) {
insert(array, position + i, newElements[i])
}
// Return the removed elements
return removed
}