我有下面的数组。
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];
其他回答
这里有一个函数解释一下:
arr.pop();
你需要这样做,因为slice不会改变原始数组。
arr = arr.slice(0, -1);
如果你想改变原始数组,你可以使用splice:
arr.splice(-1, 1);
或者流行:
arr.pop();
类的最后一个元素删除和存储时,此方法更有用 数组中。
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
在你的用例中使用下面的代码:
var arr = [1,2,3,4];
arr.pop() //returns 4 as the value
arr // value 4 is removed from the **arr** array variable
只是一张便条。当执行pop()函数时,即使该行返回了弹出的项,原始数组也会受到影响,弹出的元素也会被删除。
这是删除最后一项的好方法:
if (arr != null && arr != undefined && arr.length > 0) {
arr.splice(arr.length - 1, 1);
}
拼接细节如下:
splice(startIndex, splice的个数)