ITeye博客

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

ldbjakyo · 2012-10-26 10:02 · JavaScript · Web前端 · Markdown

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

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

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

    网上常见的方法如下: 

Javascript代码  收藏代码

  1. array = array.slice(0,i).concat( array.slice(i+1) );

    由于上述方法开销大(两次 slice),而且效率不是十分高(concat 的速度还不够快) 
所以原作者才提出了如下方法: 

Javascript代码  收藏代码

  1. Array.prototype.remove = function(from, to) {
  2. var rest = this.slice((to || from) + 1 || this.length);
  3. this.length = from < 0 ? this.length + from : from;
  4. return this.push.apply(this, rest);
  5. };

    使用方法如下: 

Javascript代码  收藏代码

  1. // Remove the second item from the array
  2. array.remove(1);
  3. // Remove the second-to-last item from the array
  4. array.remove(-2);
  5. // Remove the second and third items from the array
  6. array.remove(1,2);
  7. // Remove the last and second-to-last items from the array
  8. array.remove(-2,-1);

    如果不想扩展 Array 的 prototype 的话,也可以向下面这样写成普通函数: 

Javascript代码  收藏代码

  1. Array.remove = function(array, from, to) {
  2. var rest = array.slice((to || from) + 1 || array.length);
  3. array.length = from < 0 ? array.length + from : from;
  4. return array.push.apply(array, rest);
  5. };

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。