Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Array.splice(-1,1) remove last element in Javascript? [closed]

I was trying to remove certain elements based on their index in array. example:

var x = ["a","b","c"];

and trying to do

x.splice(x.indexOf("d"),1)

Since this turns out to be x.splice(-1,1) - it's ending up removing the element "c" from the array!

unable to understand why this is happening even though there is no cyclic property for Arrays in javascript.

like image 683
Vamshi Vangapally Avatar asked Dec 18 '22 13:12

Vamshi Vangapally


1 Answers

From the MDN page for splice:

If negative, will begin that many elements from the end.

So x.splice(-1, 1) starts one element from the end of x and deletes a single element.

like image 59
James Monger Avatar answered Apr 27 '23 17:04

James Monger