我有下面的数组。
var arr = [1,0,2];
我想删除最后一个元素,即2。
我使用了arr。slice(-1);但它并没有删除值。
我有下面的数组。
var arr = [1,0,2];
我想删除最后一个元素,即2。
我使用了arr。slice(-1);但它并没有删除值。
当前回答
// Setup
var myArray = [["John", 23], ["cat", 2]];
// Only change code below this line
var removedFromMyArray;
removedFromMyArray = myArray.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 = [ 0, 1, 2, 3, 4, 5, 6, 7 ]; // using slice arr = arr.slice(0, -1); console.log('arr : ', arr); // using splice arr.splice(-1); console.log('arr : ', arr); // using pop arr.pop(); console.log('arr : ', arr); // using shift and reverse arr.reverse().shift() arr.reverse(); console.log('arr : ', arr); // using spread Operator and reverse const [, ...exceptLast] = arr.reverse(); arr = exceptLast.reverse(); console.log('arr : ', arr); // removing last index arr.length -= 1; console.log('arr : ', arr);
// Setup
var myArray = [["John", 23], ["cat", 2]];
// Only change code below this line
var removedFromMyArray;
removedFromMyArray = myArray.pop()
你可以简单地使用arr.pop()
这将删除数组的最后一个条目。
var arr = [1,0,2];
var popped = arr.pop();//Now arr = [1,0] & popped = 2
我得到了最好的答案!
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]