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

4

14

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
Illfated answered 8/3, 2017 at 20:18 Comment(3)
It returns 1, which is a proper result.Incised
But if I am starting at index 0, and removing 1 item then why would it not return an empty array?Illfated
Because splice() returns the value which was 'spliced/cut/removed' from the original array. Try console.log(arr) and you will see that it's empty.Incised
S
21

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);
Subeditor answered 8/3, 2017 at 20:23 Comment(1)
ohh I thought it returned the modified arrayIllfated
N
3

Array.prototype.splice() returns an array of the deleted elements.

Your are logging the returned value of the operation not the current state of the array.

Nicosia answered 8/3, 2017 at 20:24 Comment(0)
A
2

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

The syntax of this method is:

array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)

You are using the second syntax and passing 0 as start and 1 as deleteCount that means you would like to start at 0th index and delete 1 item (not 1 as value in array).

This method returns an array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

So, in this case the result is [1] i.e. an array with value of 1 that is the item you just deleted.

Ahmednagar answered 8/3, 2017 at 20:25 Comment(0)
V
0

I ran into this question when I was trying to achieve a function in mini-program. A solution is to check the array's length before using the function splice. For example:

if(imgList.length > 1){
    imgList.splice(index, 1);
else{
    imgList = []
}

You can try to solve it like that.

Vitebsk answered 4/9, 2022 at 12:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.