js Array对象的扩展函数代码(2)

Array.prototype.contains = function($value)
{
 for(var $i=0; $i<this.length; $i++)
 {
  var $element = this[$i];
  if($element == $value)
   return true;
 }

return false;
}

Array.prototype.indexOf = function($value)
{
 for(var $i=0; $i<this.length; $i++)
 {
  if(this[$i] == $value)
   return $i;
 }

return -1;
}
if (!Array.prototype.lastIndexOf)
{
  Array.prototype.lastIndexOf = function(elt /*, from*/)
  {
    var len = this.length;

var from = Number(arguments[1]);
    if (isNaN(from))
    {
      from = len - 1;
    }
    else
    {
      from = (from < 0)
           ? Math.ceil(from)
           : Math.floor(from);
      if (from < 0)
        from += len;
      else if (from >= len)
        from = len - 1;
    }

for (; from > -1; from--)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
Array.prototype.insertAt = function($value, $index)
{
 if($index < 0)
  this.unshift($value);
 else if($index >= this.length)
  this.push($value);
 else
  this.splice($index, 0, $value);
}
/**
* 根据数组的下标来删除元素
*/ 
Array.prototype.removeByIndex=function($n) {  
    if($n<0){ //如果n<0,则不进行任何操作。 
      return this; 
    }else{ 
        return this.slice(0,$n).concat(this.slice($n+1,this.length)); 
    } 
}
//依赖indexOf
Array.prototype.remove = function($value)
{
 var $index = this.indexOf($value);

if($index != -1)
  this.splice($index, 1);
}

Array.prototype.removeAll = function()
{
 while(this.length > 0)
  this.pop();
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdgfsy.html