我有下面的数组。

var arr = [1,0,2];

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

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


当前回答

以身作则:

let array_1 = [1,2,3,4];
let array_2 = [1,2,3,4];
let array_3 = [1,2,3,4];
let array_4 = [1,2,3,4];

array_1.splice(-1,1)  // returned --> [4]      array_1 = [1,2,3]
array_2.slice(0,-1);  // returned --> [1,2,3]  array_2 = [1,2,3,4]
array_3.pop();        // returned --> 4        array_3 = [1,2,3]
array_4.shift();      // returned --> 1        array_4 = [2,3,4]

其他回答

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

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

以身作则:

let array_1 = [1,2,3,4];
let array_2 = [1,2,3,4];
let array_3 = [1,2,3,4];
let array_4 = [1,2,3,4];

array_1.splice(-1,1)  // returned --> [4]      array_1 = [1,2,3]
array_2.slice(0,-1);  // returned --> [1,2,3]  array_2 = [1,2,3,4]
array_3.pop();        // returned --> 4        array_3 = [1,2,3]
array_4.shift();      // returned --> 1        array_4 = [2,3,4]
var arr = [1,0,2];
arr.length--; 

//删除最后一个元素 //需要检查arr。长度为> 0

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

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

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

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

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