为js数组扩展方法

时间:2023-03-10 02:36:26
为js数组扩展方法
(function(global,undefined){
//javascript冒泡排序,直接添加到基础类型Array的原型上
Function.prototype.method = function (name, func) {
//if(!this.prototype[name]){
//先判断一下是原型中否有这个方法,如果没有再添加
this.prototype[name] = this.prototype[name] || func;
//}
return this;
}; /*Function.prototype.tool = { method:function (name, func) {
if(!this.prototype[name]){
//先判断一下是原型中否有这个方法,如果没有再添加
this.prototype[name] = func;
}
return this;
} }; tool.*/ Object.method('toString',function(){alert(33)}); /*判断Array、Function、Object、String、Number、Null、undefined、boolean类型*/
Object.method('getType',function(){
if(typeof this == "object"){
var type = Object.prototype.toString.call(this);
return type.split(" ")[1].replace("]","");
}else{
return typeof this;
}
}); //冒泡算法,左边一项跟右边每一项比
Array.method('bubble',function(){
var len = this.length;
for (j=0 ; j < len; j++) {
for (i=j+1; i<len;i++){
var first = this[i],
sec = this[j]; if (sec>first){
var tmp = this[i];
this[i] = sec;
this[j] = tmp;
}
};
};
return this;
}); //获取数组最大值
Array.method('max',function(){
return Math.max.apply(Math,this);
}); //获取数组最小值
Array.method('min',function(){
return Math.min.apply(Math,this);;
}); //删除数组中含有指定内容的一项
Array.method('delByCnt',function(cnt,flag){
if(typeof flag == 'boolean'){
if(flag){
this.splice(this.indexOf(cnt),1);
return this;
}else{
return this.splice(this.indexOf(cnt),1);
}
}else{
throw new Error("delByCnt方法的第二个参数必须是boolean类型!");
}
}); })(this);