我有下面的数组。
var arr = [1,0,2];
我想删除最后一个元素,即2。
我使用了arr。slice(-1);但它并没有删除值。
我有下面的数组。
var arr = [1,0,2];
我想删除最后一个元素,即2。
我使用了arr。slice(-1);但它并没有删除值。
当前回答
假设你有var arr = [1,0,2]
Arr.splice(-1,1)将返回数组[1,0];而arr.slice(-1,1)将返回数组[2];
其他回答
类的最后一个元素删除和存储时,此方法更有用 数组中。
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
使用展开运算符:
Const a = [1,2,3] Const[,…]Rest] = a.reverse(); const withoutLast = rest.reverse(); console.log (withoutLast)
var a = [1,2,3,4,5,6];
console.log(a.reverse().slice(1).reverse());
//Array(5) [ 1, 2, 3, 4, 5 ]
只要arr.splice(-1)就可以了。
你可以简单地使用arr.pop()
这将删除数组的最后一个条目。
var arr = [1,0,2];
var popped = arr.pop();//Now arr = [1,0] & popped = 2