JavaScript
x
7
1
var arr = [1, 2, 3, 4, 5]
2
console.log(arr)
3
//[1, 2, 3, 4, 5]
4
arr = arr.splice(4, 1)
5
console.log(arr)
6
//[5]
7
I want to remove only the last element. Why does it remove every element except the last one?
Advertisement
Answer
You need to omit the assignment.
JavaScript
1
5
1
var arr = [1, 2, 3, 4, 5]
2
console.log(arr); // [1, 2, 3, 4, 5]
3
4
arr.splice(4, 1);
5
console.log(arr); // [1, 2, 3, 4]
If you like just to delete the last one, you could take a negative index with Array#splice
. This works for any other index from the end.
JavaScript
1
5
1
var arr = [1, 2, 3, 4, 5]
2
console.log(arr); // [1, 2, 3, 4, 5]
3
4
arr.splice(-1, 1);
5
console.log(arr); // [1, 2, 3, 4]