读书人

(转) JavaScript Array Remove 最好的

发布时间: 2012-07-03 13:37:43 作者: rapoo

(转) JavaScript Array Remove 最好的删除数组元素的方法
过来看看大仙们是如何删除数组中的元素的:

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

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

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

网上常见的方法如下:

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 arrayarray.remove(1);// Remove the second-to-last item from the arrayarray.remove(-2);// Remove the second and third items from the arrayarray.remove(1,2);// Remove the last and second-to-last items from the arrayarray.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);};

读书人网 >JavaScript

热点推荐