我有下面的数组。

var arr = [1,0,2];

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

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


当前回答

var arr = [ 0, 1, 2, 3, 4, 5, 6, 7 ]; // using slice arr = arr.slice(0, -1); console.log('arr : ', arr); // using splice arr.splice(-1); console.log('arr : ', arr); // using pop arr.pop(); console.log('arr : ', arr); // using shift and reverse arr.reverse().shift() arr.reverse(); console.log('arr : ', arr); // using spread Operator and reverse const [, ...exceptLast] = arr.reverse(); arr = exceptLast.reverse(); console.log('arr : ', arr); // removing last index arr.length -= 1; console.log('arr : ', arr);

其他回答

使用splice(startPosition, deleteCount)

array.splice(-1)

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

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

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

拼接细节如下:

splice(startIndex, splice的个数)

art .slice(-1)将返回数组最后一个元素的副本,但原始数组不作修改。

要从数组中移除最后n个元素,使用arr.splice(-n)(注意“splice”中的“p”)。返回值将是一个包含已删除元素的新数组。

更简单的是,对于n == 1,使用val = arr.pop()

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

类的最后一个元素删除和存储时,此方法更有用 数组中。

var sampleArray = [1,2,3,4];// Declaring the array
var lastElement = sampleArray.pop();//this command will remove the last element of `sampleArray` and stores in a variable called `lastElement` so that you can use it if required.

现在的结果是:

console.log(sampleArray); //This will give you [1,2,3]
console.log(lastElement); //this will give you 4