(转) JavaScript Array Remove 最好的删除数组元素的方法

过来看看大仙们是如何删除数组中的元素的:

原文地址:
[url]http://ejohn.org/blog/javascript-array-remove/[/url]

作者详细的讲解了为什么要这样写,以及这些写的好处,和其它的删除方法相比它的优势是什么。所以感兴趣的读者可以仔细的看下原文。

该方法不同于网上常见的删除方法(国内搜索的结果太令人......),用原作者的话讲,该方法更加的简洁,优雅,快速,高效。

网上常见的方法如下:
array = array.slice(0,i).concat( array.slice(i+1) );

由于上述方法开销大(两次 slice),而且效率不是十分高(concat 的速度还不够快)
所以原作者才提出了如下方法:
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};

使用方法如下:
// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);

如果不想扩展 Array 的 prototype 的话,也可以向下面这样写成普通函数:
Array.remove = function(array, from, to) {
var rest = array.slice((to || from) + 1 || array.length);
array.length = from < 0 ? array.length + from : from;
return array.push.apply(array, rest);
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值