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
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
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);
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.
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.
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.
© 2022 - 2025 — McMap. All rights reserved.
1
, which is a proper result. – Incisedsplice()
returns the value which was 'spliced/cut/removed' from the original array. Tryconsole.log(arr)
and you will see that it's empty. – Incised