我有下面的数组。

var arr = [1,0,2];

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

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


当前回答

使用splice(startPosition, deleteCount)

array.splice(-1)

Var数组= ['abc','def','ghi','123']; Var remove = array.splice(-1);/ /最后一项 Console.log ('array:', array); Console.log ('removed:', removed);

其他回答

使用splice(startPosition, deleteCount)

array.splice(-1)

Var数组= ['abc','def','ghi','123']; Var remove = array.splice(-1);/ /最后一项 Console.log ('array:', array); Console.log ('removed:', removed);

使用Lodash,你可以使用dropRight,如果你不关心哪些元素被删除了:

_.dropRight([1, 2, 3])
// => [1, 2]

_.dropRight([1, 2, 3], 2);
// => [1]
var a = [1,2,3,4,5,6]; 
console.log(a.reverse().slice(1).reverse());
//Array(5) [ 1, 2, 3, 4, 5 ]

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

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

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

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

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