Skip to content Skip to sidebar Skip to footer

Array.splice Unexpected Behavior With Negative Values Index

I noticed MDN mentioned in the description of start Parameter : Index at which to start changing the array (with origin 0) If negative , will begin that many elements from the end

Solution 1:

Initially lets consider foo as ["a", "b", "c"] and foo.length is 3.

So when you are adding the element using foo.splice(-1,0,"x"), the index is calculated as foo.length - 1 which is 2.

So the new element is inserted at the index 2:

["a", "b", "c"]
  0    1    2
            ^
            |__________"x" added here 

So the new array becomes ["a", "b", "x", "c"] as "x" is inserted at index 2 and "c" is shifted by one index.

When you remove the element using foo.splice(-2,0), the index at which it is removed foo.length - 2 which is 2:

["a", "b", "x", "c"]
  0123
            ^
            |__________ "x"is removed

And the array becomes ["a", "b", "c"].

Solution 2:

Splice function accepts three parameters,

  • start: Index from where to change the array.
  • deleteCount: Number of elements to remove.
  • items(varargs): Elements to add, beginning from start index.
let foo = ["a", "b", "c"];
foo.splice(-1,0,"x") 
// I expected to added "x" as a last element// but instead it shows ["a", "b", "x", "c"]console.log(foo);

In the above code snippet, you are passing start as -1, so it's get added on last index (which is calculated as arr.length - 1) and deleteCount as 0 so no elements are deleted instead they are moved to right by one index.

Post a Comment for "Array.splice Unexpected Behavior With Negative Values Index"