从数组中删除最后一个项目

797

我有以下数组。

var arr = [1,0,2];

我想要移除最后一个元素2。

我使用了arr.slice(-1);,但它并没有移除该值。


54
使用 arr[.pop()] 方法。(该方法的具体说明请参考 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) - Tushar Gupta - curioustushar
3
arr.splice(-1,1) 将返回数组 [1,0]; arr.slice(-1,1) 将返回 [2]。 - Anja Ishmukhametova
40
arr.slice(0,-1) 对我来说是最佳解决方案。 - Black Mamba
14
这个问题有点含糊,因为“删除最后一个元素”可能意味着从数组中移除该元素并保留该数组(只是元素减少了一个)。但它也可能意味着删除该元素并保留该元素。对于第一种情况,可以使用 splice() 方法;对于第二种情况,可以使用 pop() 方法。 - thoni56
1
@Anja Ishmukhametova在2015年的评论中提到的代码格式化:"arr.splice(-1,1)会返回数组[1,0]arr.slice(-1,1)会返回[2]" - Cadoiz
显示剩余2条评论
29个回答

12

值得注意的是,slice 方法会返回一个 新的 数组,而 .pop().splice() 方法则会在 现有 的数组上进行修改。

如果你喜欢使用链式命令风格处理数据集合,那么像这样的情况你就真的需要坚持使用 slice 方法。

例如:

myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var newArrayOfThings = myArray
  .filter(x => x > 5)              // only bigly things
  .slice(0, -1)                       // get rid of the last item ! slice(-1) will give first element
  .map(x => `The number is: ${x}`);// map to a set of strings

使用"pop"进行相同类型的操作需要更多的处理和变量管理,因为与mapfilter等不同,它不会返回新数组。

push也是一样的情况,它将项添加到数组的末尾。如果使用concat,则可以保持流畅性,可能效果更好。

myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var newArrayOfThings = myArray
  .filter(x => x > 5)              // only bigly things
  .slice(-1)                       // get rid of the "10"
  .concat([100])                   // note with concat, you must pass an array
  .map(x => `The number is: ${x}`) // map to a set of strings
  


9
你可以使用splice()这两种方法之一完成:
  1. arr.splice(-1,1)
  2. arr.splice(arr.length-1,1)

splice(position_to_start_deleting, how_many_data_to_delete)接受两个参数。

position_to_start_deleting:从哪里开始删除,从0开始索引。

how_many_data_to_delete:从指定的索引开始,应该删除多少连续数据。

你也可以使用pop()来移除最后一个元素,因为pop()可以从某个数组中删除最后一个元素。请使用arr.pop()


9

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


仅减少length的副作用是否会导致内存泄漏或类似问题?(您在Joby Joseph的评论中提出的最后一个建议arr.length -= 1;)否则,这是一个简洁的解决方案。另一个注意点:如果您像第二个建议中那样使用.splice(-1,1),则可以省略,1,因为splice(-x)会删除从倒数第x个开始的所有元素。对于-x-1,从“最后一个”开始的所有元素与“最后一个”完全相同。 - Cadoiz
arr.length -= 1;arr.length = arr.length - 1; 的含义相同。 - Sahil Thummar
当然可以,但问题不在于是否存在内存泄漏或其他副作用。或者换句话说:是否有GC知道“此元素已越界,因此已删除”?之后的++arr.length给出了这样的结果:“arr:”,[0, 1, undefined],这表明它是可以的。 - Cadoiz

8

另一种方法是基于索引进行筛选:

arr.filter((element, index) => index < arr.length - 1);

注意:filter()会创建一个新的数组,而不是改变已有的数组。

6

这种方法更方便地删除和存储数组的最后一个元素。

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

这有什么不同于这个答案 - mpaskov
是的,那是真的,但这个更详细。对于初学者来说,你的回答很难理解。 - razat naik

5
var a = [1,2,3,4,5,6]; 
console.log(a.reverse().slice(1).reverse());
//Array(5) [ 1, 2, 3, 4, 5 ]

1
虽然这段代码可能回答了问题,但提供解决问题的方式和/或原因的附加上下文会提高答案的长期价值。 - Vasilisa

5

splice(index,howmany) - 这个解决方案听起来不错。但是这个howmany只适用于正数组索引。要删除最后两项或三项,请使用索引本身。

例如,使用splice(-2)删除最后两个项目。使用splice(-3)删除最后三个项目。


4
使用 Lodash,你可以使用 dropRight,如果你不关心哪些元素被删除:
_.dropRight([1, 2, 3])
// => [1, 2]

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

4
var arr = [1,0,2];
arr.length--; 

移除最后一个元素,但你可能需要先检查arr.length > 0


仅仅减小长度有副作用吗?(例如内存泄漏之类的) - Cadoiz

3

2019年ECMA5解决方案:

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

无损、通用、一行代码即可,只需在您的数组末尾进行复制和粘贴。


1
“Non destructive” 不像原问题所需的:“我想要删除最后一个元素”。这需要对原始数组进行破坏性/变异操作。 - Ben Hull

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接