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
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.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With