`
全冠清
  • 浏览: 51644 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

javascript惯用法

阅读更多
数值
/**
 * 转换&取整
 */
-45.67890^0 //-45
-45.67890|0 //-45 
~~5645.1132 //5645
'-45.67890'^0 //-45
'-45.67890'|0 //-45 
~~'5645.1132' //5645
/**
 *金额处理
 */
Number.prototype.fixMoney=function(){  
    return this.toString().replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g,"$1,")  
}  
var a=123456789  
alert(a.fixMoney()) 

数组
var a = [1,2,3];
var b = [4,5,6];
Array.prototype.push.apply(a, b);
eval(a); //[1,2,3,4,5,6]

/**
 *指定位置合并
 */ 
var a = [1,2,3,7,8,9];
var b = [4,5,6];
a.splice.apply(a, Array.concat(3, 0, b));

/**
 *最大值最小值
 */
Math.max.apply(Math, [1,2,3])  //3
Math.min.apply(Math, [1,2,3]) //1

浏览器事件
/**
 *派发(增加)事件
 */
function appendEvent(dom, event, fun){
            if (/msie/i.test(navigator.userAgent)) { //ie  
                dom.attachEvent("on" + event, fun)
            }
            else {
                dom.addEventListener(event, fun, false);
            }
        }
/**
 *取消默认事件
 */
e=e||window.event;
e.preventDefault?e.preventDefault():e.returnValue=false;

继承
var a=function(v1){  
            this.v1=v1  
            this.test=function(){  
                alert(this.v1)  
            }  
        }  
        var b=function(){  
        }  
        b.prototype=new a('12312')  
        var b1=new b('tttt')  
        b1.test()  
  
          function classA(t){  
          this.t=t  
          this.sayArg=function(){  
            alert(this.t)  
          }  
       }  
       function classB(tt){  
        this.extend=classA  
        this.extend(tt)  
        delete this.extend  
       }  
       var b2=new classB('test')  
       b2.sayArg()  
         
          function classC(cc){  
         this.c=cc  
         this.sayC=function(){  
            alert(this.c)  
         }  
       }  
       function classD(cc){  
//             classC.call(this,cc)  
             classC.apply(this,[cc])  
       }  
       var d =new classD('dddddd')  
       d.sayC()

其他
/**
 *随机数
 */
Math.random().toString(16).substring(2); //13位
Math.random().toString(36).substring(2); //11位

/**
 *赋值处理
 */
a= [b, b=a][0];//交换值
var a = b && 1; 
//相当于
if (b) {
  a = 1
}

var a = b || 1; //适合用法方法参数的默认值
//相当于
if (b) {
  a = b;
} else {
  a = 1;
}

new Array(50).join("a,")//相当于ruby,python中的"a,"*50
var date = +new Date; //转为日期的数值


//获取文件自身的位置
var path=document.scripts;   
path=path[path.length-1].src.substring(0,path[path.length-1].src.lastIndexOf("/")+1);   
if((path.indexOf('http')!=0&&path.indexOf('/')!=0)||path.indexOf('./')==0){  
            path=window.location.href.substring(0,window.location.href.lastIndexOf("/")+1)+path  
}  
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics