如何从JavaScript中删除数组中的元素?

本文翻译自:How to remove element from an array in JavaScript?

var arr = [1,2,3,5,6];

I want to remove the 1st element of the array so that it becomes: 我想删除数组的第一个元素,使其成为:

var arr = [2,3,5,6];

To extend this question, what if I want to remove the 2nd element of the array so that it becomes: 要扩展这个问题,如果我想删除数组的第二个元素,使其变为:

var arr = [1,3,5,6];

#1楼

参考:https://stackoom.com/question/8PHb/如何从JavaScript中删除数组中的元素


#2楼

The Array.prototype.shift method removes the first element from an array, and returns it. Array.prototype.shift方法从数组中删除第一个元素,并返回它。 It modifies the original array. 它修改了原始数组。

var a = [1,2,3]
// [1,2,3]
a.shift()
// 1
a
//[2,3]

#3楼

For a more flexible solution, use the splice() function. 要获得更灵活的解决方案,请使用splice()函数。 It allows you to remove any item in an Array based on Index Value: 它允许您根据索引值删除数组中的任何项:

var indexToRemove = 0;
var numberToRemove = 1;

arr.splice(indexToRemove, numberToRemove);

#4楼

也许是这样的:

arr=arr.slice(1);

#5楼

shift() is ideal for your situation. shift()非常适合您的情况。 shift() removes the first element from an array and returns that element. shift()从数组中删除第一个元素并返回该元素。 This method changes the length of the array. 此方法更改数组的长度。

array = [1, 2, 3, 4, 5];

array.shift(); // 1

array // [2, 3, 4, 5]

#6楼

Wrote a small article about inserting and deleting elements at arbitrary positions in Javascript Arrays. 写了一篇关于在Javascript Arrays中的任意位置插入和删除元素的小文章。

Here's the small snippet to remove an element from any position. 这是从任何位置删除元素的小片段。 This extends the Array class in Javascript and adds the remove(index) method. 这扩展了Javascript中的Array类,并添加了remove(index)方法。

// Remove element at the given index
Array.prototype.remove = function(index) {
    this.splice(index, 1);
}

So to remove the first item in your example, call arr.remove(): 因此,要删除示例中的第一项,请调用arr.remove():

var arr = [1,2,3,5,6];
arr.remove(0);

To remove the second item, 要删除第二个项目,

arr.remove(1);

Here's a tiny article with insert and delete methods for Array class. 这是一篇包含Array类的insert和delete方法的小文章

Essentially this is no different than the other answers using splice, but the name splice is non-intuitive, and if you have that call all across your application, it just makes the code harder to read. 基本上这与使用splice的其他答案没有什么不同,但是名称splice是非直观的,如果你在整个应用程序中都有这个调用,它只会使代码更难阅读。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值