按索引和键值删除数组元素的js函数

Array.prototype.removeIndex = function(i)
 {
   if (isNaN(i) || i > this.length)
      return false;
  this.splice(i,1);
 }
 
 Array.prototype.remove = function(key)
 {
  for (var i = 0; i < this.length; ++i)
  {
     if (this[i] == key)
         this.splice(i, 1);
  }

 }

 

   b = ['1','2','3','4','5'];
 alert("elements: "+b+"nLength: "+b.length);
 b.remove('4');       //删除值为'4'的元素
   b.removeIndex(3) //删除下标为1的元素
 alert("elements: "+b+"nLength: "+b.length);

你可能感兴趣的:(js)