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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值