Javascript 扩展array原型的几个功能函数

啰嗦一下背景:

原本的array.indexOf() 函数,不做数据类型转换。就是说查找的值是字符串就按照字符串查找,如果是数字就按照数字查找。相当于===

a = [1,2]
console.log(a.indexOf('2'))//-1
console.log(a.indexOf(2))//1

而string.indexOf(),是做数据类型转换的。无论要查找的值是字符串还是数字,都会内部转换成字符串查找。相当于==

b = '12';
console.log(b.indexOf('2'))//1
console.log(b.indexOf(2))//1

所以找到了一些array的扩展功能函数

扩展的功能函数更为强大,比如重新定义之后的array.indexOf()方法,就可以想string.indexOf()那样使用了。

Array.prototype.remove = function(index){
    if(isNaN(index)||(index>=this.length)||(index<0)) return false;
    this.splice(index,1);
    return true;
}
Array.prototype.del=function(n) {  //n表示第几项,从0开始算起。
    //prototype为对象原型,注意这里为对象增加自定义方法的方法。
    if(n<0)  //如果n<0,则不进行任何操作。
        return this;
    else
        return this.slice(0,n).concat(this.slice(n+1,this.length));
}
Array.prototype.indexOf = function(value){
    for(var i=0;i<this.length;i++){
        if(typeof(value.equals)=="function"){
            if(value.equals(this[i])) return i;
        }else if(value==this[i]) return i;
    }
    return -1;
}
Array.prototype.contains = function(value){
    return this.indexOf(value)>=0;
}
Array.prototype.clear = function(){
    while(this.length>0) this.remove(this.length-1);
}
Array.prototype.add = function(index,value){
    if(value==undefined) this.put(index);
    else{
      var len = this.length;
      this.push(this[len-1]);
      for(var i=len-1;i>index;i--) this[i] = this[i-1];
      this[index] = value;
    }
}
Array.prototype.put = function(value){
    if(!this.contains(value)) this.push(value);
}
Array.prototype.circle = function(degressive){
    if(degressive){
        var a = this[0];
        for(var i=0;i<this.length-1;i++) this[i] = this[i+1];
        this[this.length-1] = a;
    }else{
        var a = this[this.length-1];
        for(var i=this.length-1;i>0;i--) this[i] = this[i-1];
        this[0] = a;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值