我有下面的数组。

var arr = [1,0,2];

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

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


当前回答

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

其他回答

你需要这样做,因为slice不会改变原始数组。

arr = arr.slice(0, -1);

如果你想改变原始数组,你可以使用splice:

arr.splice(-1, 1);

或者流行:

arr.pop();

使用splice(startPosition, deleteCount)

array.splice(-1)

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

2019 ECMA5解决方案:

const new_arr = arr.reduce((d, i, idx, l) => idx < l.length - 1 ? [...d, i] : d, [])

非破坏性的,通用的,一行程序,只需要在数组的末尾复制粘贴。

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

stack.reverse().shift();

stack.push(0);

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

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

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

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