啰嗦一下背景:
原本的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;
}
}