欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript編程學(xué)習(xí)技巧匯總

 更新時間:2016年02月21日 11:12:19   作者:同行說  
這篇文章主要介紹了JavaScript編程學(xué)習(xí)技巧匯總,整理了編程技巧、實用函數(shù)、簡潔方法、編程細節(jié)等相關(guān)資料,感興趣的小伙伴們可以參考一下

本文實例為大家分享了JavaScript編程學(xué)習(xí)技巧,供大家參考,具體內(nèi)容如下

1、變量轉(zhuǎn)換

varmyVar="3.14159",

str=""+myVar,//tostring

int=~~myVar,//tointeger

float=1*myVar,//tofloat

bool=!!myVar,/*toboolean-anystringwithlength

andanynumberexcept0aretrue*/

array=[myVar];//toarray

但是轉(zhuǎn)換日期(new Date(myVar))和正則表達式(new RegExp(myVar))必須使用構(gòu)造函數(shù),創(chuàng)建正則表達式的時候要使用/pattern/flags這樣的簡化形式。

2、取整同時轉(zhuǎn)換成數(shù)值型

//字符型變量參與運算時,JS會自動將其轉(zhuǎn)換為數(shù)值型(如果無法轉(zhuǎn)化,變?yōu)镹aN)

'10.567890'|0

//結(jié)果:10

//JS里面的所有數(shù)值型都是雙精度浮點數(shù),因此,JS在進行位運算時,會首先將這些數(shù)字運算數(shù)轉(zhuǎn)換為整數(shù),然后再執(zhí)行運算

//|是二進制或,x|0永遠等于x;^為異或,同0異1,所以x^0還是永遠等于x;至于~是按位取反,搞了兩次以后值當(dāng)然是一樣的

'10.567890'^0

//結(jié)果:10

-2.23456789|0

//結(jié)果:-2

3、日期轉(zhuǎn)數(shù)值

//JS本身時間的內(nèi)部表示形式就是Unix時間戳,以毫秒為單位記錄著當(dāng)前距離1970年1月1日0點的時間單位

vard=+newDate();//1295698416792

4、類數(shù)組對象轉(zhuǎn)數(shù)組

vararr=[].slice.call(arguments)

下面的實例用的更絕

functiontest(){

varres=['item1','item2']

res=res.concat(Array.prototype.slice.call(arguments))//方法1

Array.prototype.push.apply(res,arguments)//方法2

}

5、進制之間的轉(zhuǎn)換

(int).toString(16);//convertsinttohex,eg12=>"C"

(int).toString(8);//convertsinttooctal,eg.12=>"14"

parseInt(string,16)//convertshextoint,eg."FF"=>255

parseInt(string,8)//convertsoctaltoint,eg."20"=>16

將一個數(shù)組插入另一個數(shù)組指定的位置

vara=[1,2,3,7,8,9];

varb=[4,5,6];

varinsertIndex=3;

a.splice.apply(a,Array.prototype.concat(insertIndex,0,b));

6、刪除數(shù)組元素

vara=[1,2,3,4,5];

a.splice(3,1);//a=[1,2,3,5]

大家也許會想為什么要用splice而不用delete,因為用delete將會在數(shù)組里留下一個空洞,而且后面的下標(biāo)也并沒有遞減。
7、判斷是否為IE

varie=/*@cc_on!@*/false;

這樣一句簡單的話就可以判斷是否為ie,太。。。

其實還有更多妙的方法,請看下面

//edithttp://www.lai18.com

//貌似是最短的,利用IE不支持標(biāo)準的ECMAscript中數(shù)組末逗號忽略的機制

varie=!-[1,];

//利用了IE的條件注釋

varie=/*@cc_on!@*/false;

//還是條件注釋

varie//@cc_on=1;

//IE不支持垂直制表符

varie='v'=='v';

//原理同上
varie=!+"v1";

學(xué)到這個瞬間覺得自己弱爆了。

盡量利用原生方法

要找一組數(shù)字中的最大數(shù),我們可能會寫一個循環(huán),例如:

varnumbers=[3,342,23,22,124];

varmax=0;

for(vari=0;i

if(numbers[i]>max){

max=numbers[i];

}

}

alert(max);

其實利用原生的方法,可以更簡單實現(xiàn)

varnumbers=[3,342,23,22,124];

numbers.sort(function(a,b){returnb-a});

alert(numbers[0]);

當(dāng)然最簡潔的方法便是:

Math.max(12,123,3,2,433,4);//returns433

當(dāng)前也可以這樣

[xhtml]view plaincopy

Math.max.apply(Math,[12,123,3,2,433,4])//取最大值

Math.min.apply(Math,[12,123,3,2,433,4])//取最小值

8、生成隨機數(shù)

Math.random().toString(16).substring(2);//toString()函數(shù)的參數(shù)為基底,范圍為2~36。

Math.random().toString(36).substring(2);

不用第三方變量交換兩個變量的值

a=[b,b=a][0];

9、事件委派

js代碼如下:

//Classiceventhandlingexample

(function(){

varresources=document.getElementById('resources');

varlinks=resources.getElementsByTagName('a');

varall=links.length;

for(vari=0;i

//Attachalistenertoeachlink

links[i].addEventListener('click',handler,false);

};

functionhandler(e){

varx=e.target;//Getthelinkthatwasclicked

alert(x);

e.preventDefault();

};

})();

利用事件委派可以寫出更加優(yōu)雅的:

(function(){

varresources=document.getElementById('resources');

resources.addEventListener('click',handler,false);

functionhandler(e){

varx=e.target;//getthelinktha

if(x.nodeName.toLowerCase()==='a'){

alert('Eventdelegation:'+x);

e.preventDefault();

}

};

})();

10、檢測ie版本

var_IE=(function(){

varv=3,div=document.createElement('div'),all=div.getElementsByTagName('i');

while(

div.innerHTML='',

all[0]

);

returnv>4?v:false;

}());

javaScript版本檢測

你知道你的瀏覽器支持哪一個版本的Javascript嗎?

varJS_ver=[];

(Number.prototype.toFixed)?JS_ver.push("1.5"):false;

([].indexOf&&[].forEach)?JS_ver.push("1.6"):false;

((function(){try{[a,b]=[0,1];returntrue;}catch(ex){returnfalse;}})())?JS_ver.push("1.7"):false;

([].reduce&&[].reduceRight&&JSON)?JS_ver.push("1.8"):false;

("".trimLeft)?JS_ver.push("1.8.1"):false;

JS_ver.supports=function()

{

if(arguments[0])

return(!!~this.join().indexOf(arguments[0]+",")+",");

else

return(this[this.length-1]);

}

alert("LatestJavascriptversionsupported:"+JS_ver.supports());

alert("Supportforversion1.7:"+JS_ver.supports("1.7"));

11、判斷屬性是否存在

//BAD:Thiswillcauseanerrorincodewhenfooisundefined

if(foo){

doSomething();

}
//GOOD:Thisdoesn'tcauseanyerrors.However,evenwhen

//fooissettoNULLorfalse,theconditionvalidatesastrue

if(typeoffoo!="undefined"){

doSomething();

}
//BETTER:Thisdoesn'tcauseanyerrorsandinaddition

//valuesNULLorfalsewon'tvalidateastrue

if(window.foo){

doSomething();

}

有的情況下,我們有更深的結(jié)構(gòu)和需要更合適的檢查的時候

//UGLY:wehavetoproofexistenceofevery

//objectbeforewecanbesurepropertyactuallyexists

if(window.oFoo&&oFoo.oBar&&oFoo.oBar.baz){

doSomething();

}

其實最好的檢測一個屬性是否存在的方法為:

if("opera"inwindow){

console.log("OPERA");

}else{

console.log("NOTOPERA");

}

12、檢測對象是否為數(shù)組

varobj=[];

Object.prototype.toString.call(obj)=="[objectArray]";

以上就是本文的全部內(nèi)容,希望對大家學(xué)習(xí)javascript程序設(shè)計有所幫助。

相關(guān)文章

最新評論