我有下面的数组。

var arr = [1,0,2];

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

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


当前回答

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

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

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

其他回答

我得到了最好的答案!

var array = [1, 2, 3, 4]
array.length = array.length - 1

console.log(array)
> [1, 2, 3]

老实说,JS在这一点上是一个迷因。

PS:这会影响变量和它的任何引用,如果你不想影响变量的任何引用,你可以这样做:

var array = [1, 2, 3, 4]
var modifiedArray = Array.from(array)
modifiedArray .length = modifiedArray .length - 1

console.log(modifiedArray )
> [1, 2, 3]

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

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

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

这里有一个函数解释一下:

arr.pop();

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

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

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

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

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