我有下面的数组。
var arr = [1,0,2];
我想删除最后一个元素,即2。
我使用了arr。slice(-1);但它并没有删除值。
我有下面的数组。
var arr = [1,0,2];
我想删除最后一个元素,即2。
我使用了arr。slice(-1);但它并没有删除值。
当前回答
var stack = [1,2,3,4,5,6];
stack.reverse().shift();
stack.push(0);
输出为:Array[0,1,2,3,4,5]。 这将允许您在插入新值时保持相同数量的数组元素。
其他回答
splice(index,howmany) -这个解决方案听起来不错。但是This howmany只适用于正数组下标。若要删除最后两项或三项,请使用索引本身。
例如,使用splice(-2)删除最后两项。拼接(-3)用于移除最后三个项目。
使用展开运算符:
Const a = [1,2,3] Const[,…]Rest] = a.reverse(); const withoutLast = rest.reverse(); console.log (withoutLast)
我认为.pop()是最“正确”的解决方案,然而,有时它可能不起作用,因为你需要使用数组没有最后一个元素在那里…
在这种情况下,你可能想使用下面的代码,它将返回[1,2,3]
var arr = [1,2,3,4]; console.log(arr.splice(0,arr.length-1));
而.pop()将返回4:
Var arr = [1,2,3,4]; console.log (arr.pop ());
这可能并不可取……
希望这能为您节省一些时间。
var arr = [1,0,2];
arr.length--;
//删除最后一个元素 //需要检查arr。长度为> 0
类的最后一个元素删除和存储时,此方法更有用 数组中。
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