js 数组操作

来源:互联网 发布:手机解压软件 编辑:程序博客网 时间:2024/05/18 13:23
 

1,查看数组中是否存在某个元素
Array.prototype.in_array = function(value)  { 
 for(i = 0; i < this.length; i++)  { 
  if(this[i] == value) 
  return true; 
  } 
 return false; 
}

2,得到元素在数组的索引
Array.prototype.getIndexByValue= function(value) 

    var index = -1; 
    for (var i = 0; i < this.length; i++) 
    { 
        if (this[i] == value) 
        { 
            index = i; 
            break; 
        } 
    } 
    return index; 

3,通过索引删除元素
Array.prototype.remove=function(value) 

    if(isNaN(value) || value>this.length){
  return false;
 } 
    for(var i = 0,n = 0; i < this.length; i++) 
    { 
        if(this[i] != this[value]) 
        { 
            this[n++] = this[i] 
        } 
    } 
    this.length-=1 
}

Array.prototype.baoremove = function(dx) 
 { 
  if(isNaN(dx) || dx > this.length){
  return false;
 } 
  this.splice(dx,1); 
 }

原创粉丝点击