本文翻译自:Remove last item from array
I have the following array. 我有以下数组。
var arr = [1,0,2];
I would like to remove the last element ie 2. 我想删除最后一个元素,即2。
I used arr.slice(-1);
我用了arr.slice(-1);
but it doesn't remove the value. 但不会删除该值。
#1楼
参考:https://stackoom.com/question/1K0P6/从数组中删除最后一项
#2楼
You would need to do this since slice
doesn't alter the original array. 您将需要执行此操作,因为slice
不会更改原始数组。
arr = arr.slice(-1);
If you want to alter the original array you can use splice
: 如果要更改原始数组,可以使用splice
:
arr.splice(-1, 1);
or pop
: 或pop
:
arr.pop();
#3楼
arr.splice(-1,1)
#4楼
Array.prototype.pop() by JavaScript convention. Array.prototype.pop()通过JavaScript约定。
let fruit = ['apple', 'orange', 'banana', 'tomato'];
let popped = fruit.pop();
console.log(popped); // "tomato"
console.log(fruit); // ["apple", "orange", "banana"]
#5楼
有一个功能, 在这里解释:
arr.pop();
#6楼
You could simply use, arr.pop()
您可以简单地使用arr.pop()
This removes the last entry of the array. 这将删除数组的最后一个条目。
var arr = [1,0,2];
var popped = arr.pop();//Now arr = [1,0] & popped = 2