Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't array.splice() work when the array has only 1 element?

Is this intended behavior? I would expect an empty array to be returned here.

JavaScript

let arr = [1];
console.log(arr.splice(0, 1))

Console

1
like image 642
Jim Moody Avatar asked Mar 08 '17 20:03

Jim Moody


People also ask

Why is splice not working on array?

It's not working because you are removing items from the array while looping through the keys. When you remove an item, it will rearrange the other items depending on how the array is implemented internally, and you end up with a loop that doesn't iterate over the keys that you expect.

Does splice work on arrays?

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

Why is splice returning empty array?

splice function splices an array returns the elements that were removed. Since you are not removing anything and just using it to insert an element, it will return the empty array.

How do you splice an element from an array?

Find the index of the array element you want to remove using indexOf , and then remove that index with splice . The splice() method changes the contents of an array by removing existing elements and/or adding new elements. The second parameter of splice is the number of elements to remove.


1 Answers

Because it returns what was removed, which is [1] in your case. arr will be empty after the call.

See example:

let arr = [1];
arr.splice(0, 1);
console.log(arr);
like image 64
gerrit Avatar answered Nov 15 '22 20:11

gerrit