JavaScript中Array的prototype运用

<script>  
 /* 
  *  方法:Array.removeAt(Index) 
  *  功能:删除数组元素. 
  *  参数:Index删除元素的下标. 
  *  返回:在原数组上修改数组 
  */ 
  
 Array.prototype.removeAt=function(Index) 
 { 
  if(isNaN(Index)||Index>this.length){return false;} 
  for(var i=0,n=0;i<this.length;i++) 
  { 
   if(this[i]!=this[Index]) 
   { 
       this[n++]=this[i] 
   } 
  } 
  this.length-=1 
 } 
              
 /*                             
  *  方法:Array.remove(obj)      
  *  功能:删除数组元素.         
  *  参数:要删除的对象.     
  *  返回:在原数组上修改数组    
  */                            
                                
 Array.prototype.remove=function(obj) 
 { 
  if(null==obj){return;} 
  for(var i=0,n=0;i<this.length;i++) 
  { 
   if(this[i]!=obj) 
   { 
    this[n++]=this[i]; 
   } 
  } 
  this.length-=1 
 } 
  
 /*                             
  *  方法:Array.Contains(obj)      
  *  功能:确定某个元素是否在数组中.         
  *  参数:要查找的Object对象 
  *  返回:找到返回true,否则返回false; 
  */                                                 
 Array.prototype.Contains=function(obj) 
 { 
  if(null==obj){return;} 
  for(var i=0,n=0;i<this.length;i++) 
  { 
   if(this[i]!=obj) 
   { 
    return true; 
   } 
  } 
   
  return false; 
 } 
  
  
 /*                             
  *  方法:Array.IndexOf(obj)      
  *  功能:搜索指定的Object,并返回第一个匹配项从零开始的索引         
  *  参数:要查找的Object对象    
  *  返回:找到返回该元素在数组中的索引,否则返回-1 
  */   
 Array.prototype.IndexOf=function(obj) 
 { 
  if(null==obj){return;} 
  { 
   for(var i=0,n=0;i<this.length;i++) 
   { 
    if(this[i]==obj) 
    { 
     return i; 
    } 
   }    
  } 
   
  return -1; 
 } 
  
 /*                             
  *  方法:Array.Clear()      
  *  功能:消空数组元素.         
  *  参数:无.     
  *  返回:空数组 
  */   
 Array.prototype.Clear=function()                                    
 {                                                                   
  this.length=0;                                              
 }     
 
</script>  

 

在JavaScript中可以用prototype来扩展已有类增加自己的方法,在这里提供对Array的扩展可减少许多工作量。

 

排序的做法:

<script type="text/javascript">

function sortNumber(a,b)
{
return a - b
}

var arr = new Array(6)
arr[0] = "10"
arr[1] = "5"
arr[2] = "40"
arr[3] = "25"
arr[4] = "1000"
arr[5] = "1"

document.write(arr + "<br />")
document.write(arr.sort(sortNumber))

</script>
<script type="text/javascript">
var ay = [{id:1,name:"wxw1",num:1},{id:2,name:"wxw2",num:7},{id:3,name:"wxw3",num:5},{id:4,name:"wxw4",num:6}]
ay.sort(function(a,b){
    return a.num-b.num;
    })
for(var a in ay){
  alert(ay[a].id);    
}
</script>

 

posted @ 2013-04-25 21:35  网络虫  阅读(381)  评论(0编辑  收藏  举报