使用JavaScript从数组中删除项目

One operation that seems to be more difficult than it should be in every programming language is removing a value from an array.  It's such an easy concept mentally that it skews our programmatic view of the task.  In JavaScript the splice method is of huge help in removing an item from an array.

一种似乎比每种编程语言都要困难的操作是从数组中删除一个值。 从心理上讲,这是一个简单的概念,它歪曲了我们对该任务的编程观点。 在JavaScript中,拼接方法在从数组中删除项目方面有很大帮助。

JavaScript拼接 (JavaScript Splice)

One splice coupled with an indexOf removes the item from an array:

一个结合有indexOf splice将从数组中删除该项目:


// Start with an initial array
var array = ["a", "b", "c"];

// Find and remove item from an array
var i = array.indexOf("b");
if(i != -1) {
	array.splice(i, 1);
}


Of course if you'd like to remove multiple occurrences of the same string/number, you'll need add a bit more logic:

当然,如果您想删除同一字符串/数字的多次出现,则需要添加一些逻辑:


for(var i = array.length-1; i--;){
	if (array[i] === "b") array.splice(i, 1);
}


You may be thinking that the filter method would work...

您可能会认为filter方法会起作用...


array.filter(function(i) {
	return i != "b"
});


...but that will return a new array, thus not modifying the original.

...但是这将返回一个新数组,因此不会修改原始数组。

Removing a given value from an array isn't too difficult of a task when you have a reliable snippet nearby!

当附近有可靠的代码段时,从数组中删除给定值并不是一件容易的事!

翻译自: https://davidwalsh.name/remove-item-array-javascript

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值