我有下面的数组。

var arr = [1,0,2];

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

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


当前回答

在你的用例中使用下面的代码:

var arr = [1,2,3,4];
arr.pop() //returns 4 as the value
arr // value 4 is removed from the **arr** array variable

只是一张便条。当执行pop()函数时,即使该行返回了弹出的项,原始数组也会受到影响,弹出的元素也会被删除。

其他回答

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

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

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

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

2019 ECMA5解决方案:

const new_arr = arr.reduce((d, i, idx, l) => idx < l.length - 1 ? [...d, i] : d, [])

非破坏性的,通用的,一行程序,只需要在数组的末尾复制粘贴。

在你的用例中使用下面的代码:

var arr = [1,2,3,4];
arr.pop() //returns 4 as the value
arr // value 4 is removed from the **arr** array variable

只是一张便条。当执行pop()函数时,即使该行返回了弹出的项,原始数组也会受到影响,弹出的元素也会被删除。

// Setup
var myArray = [["John", 23], ["cat", 2]];

// Only change code below this line
var removedFromMyArray;
removedFromMyArray = myArray.pop()