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
} 相关推荐
zrtlin 2020-11-09
wikiwater 2020-10-27
heheeheh 2020-10-19
Crazyshark 2020-09-15
ZGCdemo 2020-08-16
jczwilliam 2020-08-16
littleFatty 2020-08-16
idning 2020-08-03
jinxiutong 2020-07-26
lanzhusiyu 2020-07-19
Skyline 2020-07-04
xiaofanguan 2020-06-25
Aveiox 2020-06-23
dragonzht 2020-06-17