日期:2014-05-16  浏览次数:20421 次

js绗旇1
1銆佷笉浣跨敤var鍒涘缓鐨勫彉閲忥紝鏄殣鍚殑鍏ㄥ眬鍙橀噺锛屽敖绠″畠鏄湪鍑芥暟鍐呴儴鍒涘缓鐨勶紝鍙互浣跨敤delete鎿嶄綔绗﹀垹闄ゃ€傝繖琛ㄦ槑闅愬惈鍏ㄥ眬鍙橀噺涓ユ牸鏉ヨ涓嶆槸鐪熸鐨勫彉閲忥紝鑰屾槸鍏ㄥ眬瀵硅薄鐨勫睘鎬э紝灞炴€у彲鍒犻櫎銆?pre class="javascript" name="code">
(function(){
 global_var=3;
}())
alert(global_var);//alert 3


2銆乯avascript鍏佽鍦ㄥ嚱鏁扮殑浠讳綍鍦版柟澹版槑澶氫釜鍙橀噺锛屾棤璁哄湪鍝0鏄庯紝鏁堟灉閮界瓑浜庡湪鍑芥暟椤堕儴杩涜澹版槑銆傝繖灏辨槸鎵€璋撶殑鈥滄彁鍗団€濄€?
myname="global";
function func(){
   alert(myname);//鈥渦ndefined鈥?
    var myname="local";
   alert(myname);//灞€閮ㄥ彉閲?
}


3銆乫or寰幆缁忓父鐢ㄥ湪閬嶅巻鏁扮粍鎴栬€呯被鏁扮粍瀵硅薄銆?
寤鸿浣跨敤浠ヤ笅鏍煎紡锛?
var i,marry=[];
for ( i = marry.length; i--;){
    //do something
}

  • 浣跨敤鏈€灏戠殑鍙橀噺
  • 閫愭鍑忚嚦0锛岄€氬父鏇村揩锛屽洜涓哄悓0姣旇緝姣斿悓鏁扮粍闀垮害锛屾垨鑰呴潪0鏁扮粍姣旇緝鏇存湁鏁堢巼


4銆乫or-in 寰幆
閫氬父鐢ㄤ簬閬嶅巻闈炴暟缁勫璞★紝鎶€鏈笂鏉ヨ涔熷彲浠ョ敤浜庨亶鍘嗘暟缁勶紙鍦╦avascript涓紝鏁扮粍涔熸槸瀵硅薄锛夈€?
   褰撻亶鍘嗗璞″睘鎬ф潵杩囨护閬囧埌鍘熷瀷閾剧殑灞炴€ф椂锛屼娇鐢╤asOwnProperty()鏂规硶銆?

5銆侀殣寮忕被鍨嬭浆鎹㈠簲璇ラ伩鍏嶄娇鐢?
javascript鍦ㄤ娇鐢ㄦ瘮杈冭鍙ユ椂浼氭墽琛岄殣寮忕被鍨嬭浆鎹紝杩欎篃鏄负浠€涔堟墽琛?false==0鎴栬€?"==0杩欑被姣旇緝璇彞鍚庢倲杩斿洖true锛?
var zero=0;
if(zero===false){
//鎵ц涓ユ牸鐨勭瓑浠锋瘮杈?浠g爜鏈墽琛?
}
if(zero==false){
//闅愬紡绫诲瀷杞崲锛岃繖鍧椾唬鐮佷細琚墽琛?
}


6銆侀伩鍏嶄娇鐢╡val()
eval()鍙互灏嗕换鎰忓瓧绗︿覆褰撳仛涓€涓猨avascript浠g爜鏉ユ墽琛屻€傚鏋滀唬鐮佹槸杩愯鏃跺姩鎬佺敓鎴愮殑锛屽缓璁敤鍏朵粬鏂规硶鏉ユ浛浠c€?

//涓嶅缓璁?
var property="name";
alert(eval("obj."+property));

//寤鸿
var property="name";
alert(obj[property]);

//涓嶅缓璁?
setTimeout("myFunc()", 1000);

//寤鸿
setTimeout(myFunc, 1000);



濡傛灉涓€瀹氳浣跨敤eval()锛屽彲浠ヨ€冭檻浣跨敤new Function()鏉ユ浛浠val().
濂藉锛歯ew Functon()涓殑浠g爜鍦ㄥ眬閮ㄥ嚱鏁颁腑杩愯锛屼换浣?strong>閲囩敤var瀹氫箟鐨勫彉閲忛兘涓嶄細鑷姩鎴愪负鍏ㄥ眬鍙橀噺銆?
涔熷彲浠ュ皢eval璋冪敤灏佽鍒颁竴涓嵆鏃跺嚱鏁颁腑銆?
var jsstring="var un=1;console.log(un);";
eval(jsstring);//un鍏ㄥ眬鍙橀噺

jsstring="var deux=2;console.log(deux);";
new Function(jstring)());//Function涓巒ew Function鏄竴鏍风殑銆俤eux灞€閮ㄥ彉閲?

jsstring="var trois=3;console.log(trois);";
(function(){
    eval(jsstring);
}());//鍗虫椂鍑芥暟锛宼rois灞€閮ㄥ彉閲?


鍙︿竴涓猲ew Functon()鍜宔val()鐨勫尯鍒湪浜巈val()浼氬奖鍝嶅埌浣滅敤鍩熼摼锛岃€屾棤璁哄湪鍝墽琛孎unction()瀹冮兘浠呬粎鑳界湅鍒板叏鍓т綔鐢ㄥ煙銆?
(function(){
    var local=1;
    eval("local=3;console.log(local);");// logs 3
    console.log(local);//logs 3
}());

(function(){
    var local=1;
    Function("console.log(local);")();//logs undefined
}());


7銆佷娇鐢╬arseInt()鐨勬暟鍊肩害瀹?
parseInt()鏈€濂藉姞涓婅繘鍒跺弬鏁帮紝parseInt("12",10);
鍙︿竴涓皢瀛楃涓茶浆鎹负鏁板€肩殑鏂规硶鏄細
   +"08"; //缁撴灉鏄?
   Number("08");//缁撴灉鏄?
杩欑鏂规硶閫氬父浼氭瘮parseInt()蹇緢澶氾紝parseInt()鏄В鏋愪笉鏄浆鎹€?
浣嗗鏋滆緭鍏?08  hello",闄や簡parseInt()鍏朵粬鏂规硶閮戒細澶辫触骞惰繑鍥濶aN銆?

8銆佹鏌ユ槸鍚︽暟缁?
鍙互浣跨敤Array.isArray(arg);
濡傛灉涓嶈兘鐢ˋrray.isArray()鍙互浣跨敤濡備笅褰㈠紡杩涜妫€鏌?
if(typeof Array.isArray === "undefined"){
    Array.isArray=function(arg){
        return Object.prototype.toString.call(arg)==='[object Array]';
    };
}