给数组添加remove功能

发现jQuery作者John Resig写的一个方法:

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);
  }

 

console.info(Array);
  var array = ["one","two","three","four","five","six"];
  console.info(array);
  var array = ["one","two","three","four","five","six"];
  array.remove(0);//删除第一个元素
  console.info(array);
  var array = ["one","two","three","four","five","six"];
  array.remove(-1);//删除倒数一个元素
  console.info(array);
  var array = ["one","two","three","four","five","six"];
  array.remove(0,2);//删除数组中下标为0-2的元素(3个)
  console.info(array);

 /**
  也就是说,remove接受两个参数,第一个参数为起始下标,第二个参数为结束下标,其中第二个参数可以忽略,
  这种情况下会删除指定下标的元素。当然,不是每个人都希望影响整个原型链(原因在下一个小节里讨论)
  ,因此可以考虑另一种方式:
  */
  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);
  }
  /**
  其操作方式与前者并无二致,但是不影响全局对象,代价是你需要显式的传递需要操作的数组作为第一个参数:
  */
  var array = ["one","two","three","four","five","six"];
  Array.remove(array,0,2);//删除0,1,2三个元素
  console.info(array);

 

你可能感兴趣的:(给数组添加remove功能)