zoukankan      html  css  js  c++  java
  • 为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);
  • 相关阅读:
    Linux 或 Windows 上实现端口映射
    请收藏,Linux 运维必备的 40 个命令总结,收好了~
    收藏:存储知识全面总结
    超详干货!Linux 环境变量配置全攻略
    iv012-LockSupport
    iv011-死锁编码及定位分析
    iv010-线程池
    iv009-Callable接口
    iv008-线程之间通信之生产者消费者
    iv007-synchronized和Lock的区别
  • 原文地址:https://www.cnblogs.com/macliu/p/5238708.html
Copyright © 2011-2022 走看看