我有下面的数组。

var arr = [1,0,2];

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

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


当前回答

这是删除最后一项的好方法:

if (arr != null && arr != undefined && arr.length > 0) {
      arr.splice(arr.length - 1, 1);
}

拼接细节如下:

splice(startIndex, splice的个数)

其他回答

使用splice(startPosition, deleteCount)

array.splice(-1)

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

只要arr.splice(-1)就可以了。

使用JavaScript约定的Array.prototype.pop()。

let fruit = ['apple', 'orange', 'banana', 'tomato'];
let popped = fruit.pop();

console.log(popped); // "tomato"
console.log(fruit); // ["apple", "orange", "banana"]

使用展开运算符:

Const a = [1,2,3] Const[,…]Rest] = a.reverse(); const withoutLast = rest.reverse(); console.log (withoutLast)

2019 ECMA5解决方案:

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

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