我有下面的数组。

var arr = [1,0,2];

我想删除最后一个元素,即2。

我使用了arr。slice(-1);但它并没有删除值。


当前回答

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);

其他回答

以身作则:

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]

使用JavaScript约定的Array.prototype.pop()。

let fruit = ['apple', 'orange', 'banana', 'tomato'];
let popped = fruit.pop();

console.log(popped); // "tomato"
console.log(fruit); // ["apple", "orange", "banana"]

使用Lodash,你可以使用dropRight,如果你不关心哪些元素被删除了:

_.dropRight([1, 2, 3])
// => [1, 2]

_.dropRight([1, 2, 3], 2);
// => [1]

使用展开运算符:

Const a = [1,2,3] Const[,…]Rest] = a.reverse(); const withoutLast = rest.reverse(); console.log (withoutLast)

使用splice(startPosition, deleteCount)

array.splice(-1)

Var数组= ['abc','def','ghi','123']; Var remove = array.splice(-1);/ /最后一项 Console.log ('array:', array); Console.log ('removed:', removed);