我有下面的数组。

var arr = [1,0,2];

我想删除最后一个元素,即2。

我使用了arr。slice(-1);但它并没有删除值。


当前回答

另一种方法是基于索引进行过滤:

arr.filter((element, index) => index < arr.length - 1);

注意:filter()创建新数组,不改变现有数组。

其他回答

var stack = [1,2,3,4,5,6];

stack.reverse().shift();

stack.push(0);

输出为:Array[0,1,2,3,4,5]。 这将允许您在插入新值时保持相同数量的数组元素。

splice(index,howmany) -这个解决方案听起来不错。但是This howmany只适用于正数组下标。若要删除最后两项或三项,请使用索引本身。

例如,使用splice(-2)删除最后两项。拼接(-3)用于移除最后三个项目。

// Setup
var myArray = [["John", 23], ["cat", 2]];

// Only change code below this line
var removedFromMyArray;
removedFromMyArray = myArray.pop()

如果你想在javascript中从数组的末尾删除n个项目,你可以很容易地使用:

arr.splice(-n, n);

在你的用例中使用下面的代码:

var arr = [1,2,3,4];
arr.pop() //returns 4 as the value
arr // value 4 is removed from the **arr** array variable

只是一张便条。当执行pop()函数时,即使该行返回了弹出的项,原始数组也会受到影响,弹出的元素也会被删除。