我有下面的数组。
var arr = [1,0,2];
我想删除最后一个元素,即2。
我使用了arr。slice(-1);但它并没有删除值。
我有下面的数组。
var arr = [1,0,2];
我想删除最后一个元素,即2。
我使用了arr。slice(-1);但它并没有删除值。
当前回答
你可以用两种方式使用splice():
Arr. Splice (1, 1) Arr. Splice (arr. Length - 1, 1)
Splice (position_to_start_deleting, how_many_data_to_delete)有两个参数。
position_to_start_deleting:开始删除的从零开始的索引。 how_many_data_to_delete:从指定的索引删除连续数据的数量。
您还可以使用pop()删除最后一个元素,因为pop()会从某个数组中删除最后一个元素。 使用arr.pop ()
其他回答
以身作则:
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 stack = [1,2,3,4,5,6];
stack.reverse().shift();
stack.push(0);
输出为:Array[0,1,2,3,4,5]。 这将允许您在插入新值时保持相同数量的数组元素。
类的最后一个元素删除和存储时,此方法更有用 数组中。
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
你需要这样做,因为slice不会改变原始数组。
arr = arr.slice(0, -1);
如果你想改变原始数组,你可以使用splice:
arr.splice(-1, 1);
或者流行:
arr.pop();
使用splice(startPosition, deleteCount)
array.splice(-1)
Var数组= ['abc','def','ghi','123']; Var remove = array.splice(-1);/ /最后一项 Console.log ('array:', array); Console.log ('removed:', removed);