1、取URL中的參數 function getParameterByName(name) { var match = RegExp('[?&]' + name + '=([^&]*)') .exec(window.location.search); return match && decodeURIComponent(match[1].replace(/\+/g, ' ')); } 2、正則分組 var testStr="<div><img src='/a.jpg' alt='' /><span>test</span><img src='/b.jpg' alt='' /><span>TTest</span><img src='/c.png' alt='' /></div>"; var reg=/<img\ssrc='(.*?)'\s+alt=''\s*\/>/g; var match=reg.exec(testStr),results=[]; while(match != null){ results.push(match[1]); match=reg.exec(testStr); } console.log(results); /* Array ["/a.jpg", "/b.jpg", "/c.png"] */ 3、爲何parseInt(1/0,19)的結果爲18 1/0的結果是Infinity,因此parseInt(1/0,19)等同於parseInt("Infinity",19),而在19進制中: 19進制 10進制 -------------------- 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 a 10 b 11 c 12 d 13 e 14 f 15 g 16 h 17 i 18 i表示18,因此parseInt(1/0,19)的結果爲18。 4、jQuery中獲取設置checkbox選中狀態 因爲在jQuery1.6之後.attr("checked")的返回結果是 checked,因此通常用下面兩種方法獲取選中狀態: $("#checkboxID").is(":checked"); //jQuery 1.6 + $("#checkboxID").prop("checked"); 選中checkbox: //jQuery 1.6+ $("#checkboxID").prop("checked", true); $("#checkboxID").prop("checked", false); //jQuery 1.5 and below $('#checkboxID').attr('checked','checked') $('#checkboxID').removeAttr('checked') 5、jQuery中判斷一個元素是否存在 if ($(selector).length) 6、用JavaScript對URL進行編碼 var myUrl = "http://example.com/index.html?param=1&anotherParam=2"; var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl); 7、jQuery中event.preventDefault() 與 return false 的區別 //Demo1 event.preventDefault() $('a').click(function (e) { // custom handling here e.preventDefault(); }); //Demo2 return false $('a').click(function () { // custom handling here return false; }; jQuery中return false至關於同時調用e.preventDefault 和 e.stopPropagation。 要注意的是,在原生js中,return false僅僅至關於調用了e.preventDefault。 8、JavaScript檢查一個字符串是否爲空最簡單的方法 if (strValue) { //do something } 9、用JavaScript添加和刪除class //Add Class document.getElementById("MyElement").className += " MyClass"; //Remove Class document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/(?:^|\s)MyClass(?!\S)/,''); 10、在jQuery中取消一個ajax請求 var xhr = $.ajax({ type: "POST", url: "test.php", data: "name=test", success: function(msg){ alert( msg ); } }); //取消請求 xhr.abort() 要注意的是,在ajax請求未響應以前能夠用xhr.abort()取消,但若是請求已經到達了服務器端,這樣作的結果僅僅是讓瀏覽器再也不監聽這個請求的響應,但服務器端仍然會進行處理。 11、JavaScript刪除數組中的項 delete vs splice var myArray=["a","b","c"]; delete myArray[0]; for(var i=0,j=myArray.length;i<j;i++){ console.log(myArray[i]); /* undefined b c */ } var myArray2=["a","b","c"]; myArray2.splice(0,1); for(var i=0,j=myArray2.length;i<j;i++){ console.log(myArray2[i]); /* b c */ } 上面的代碼已經說明區別了,一個是設置爲undefined,一個是真正的刪除了。 12、JavaScript中16進制與10進制相互轉換 var sHex=(255).toString(16);//ff var iNum=parseInt("ff",16);//255 十3、JavaScript多行字符串 如何在JavaScript中方便地寫一個多行字符串呢,有三種方案,你本身選吧: //one var testHtml="a"+ "b"+ "c"; //two var testHtml2="a\ b\ c"; //three var testHtml3=["a", "b", "c"].join(""); 十4、JavaScript中!!操做符是什麼 console.log(!!10);//true console.log(!!0);//false console.log(!!"abc");//true console.log(!!"");//false 簡單地說就是把右側的值轉爲bool值 十5、JavaScript實現endsWith String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; //or function endsWith(str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; } 十6、JavaScript中克隆對象 function clone(obj) { // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { var copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { var copy = []; for (var i = 0, var len = obj.length; i < len; ++i) { copy[i] = clone(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { var copy = {}; for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); } 十7、JavaScript字符與ASCII碼間的轉換 console.log("\n".charCodeAt(0));//10 console.log(String.fromCharCode(65));//A 十8、JavaScript中浮點數的相等判斷不能用 == console.log(0.1+0.2 == 0.3);//false console.log(Math.abs(0.1+0.2 - 0.3) < 0.000001);//true 如上所示,浮點數相等判斷要用差的絕對值小於某一個數來判斷。至於緣由能夠參考這裏:http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html 十9、JavaScript中base64編碼 var Base64 = { // private property _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", // public method for encoding encode : function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = Base64._utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); } return output; }, // public method for decoding decode : function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = this._keyStr.indexOf(input.charAt(i++)); enc2 = this._keyStr.indexOf(input.charAt(i++)); enc3 = this._keyStr.indexOf(input.charAt(i++)); enc4 = this._keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = Base64._utf8_decode(output); return output; }, // private method for UTF-8 encoding _utf8_encode : function (string) { string = string.replace(/\r\n/g,"\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }, // private method for UTF-8 decoding _utf8_decode : function (utftext) { var string = ""; var i = 0; var c = c1 = c2 = 0; while ( i < utftext.length ) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } } //encode Base64.encode("Test"); //VGVzdA== //decode Base64.decode("VGVzdA=="); // Test 二10、jQuery中each跟map的區別 each跟map均可以用來遍歷Array或Object,區別是each不改變原來的Array或Object,map是操做給定的Array或Object返回一個新Array或Object。Demo: var items = [1,2,3,4]; $.each(items, function() { alert('this is ' + this);//alert 1,2,3,4 }); var newItems = $.map(items, function(i) { return i + 1; }); // newItems is [2,3,4,5] map會佔用更多的內存,因此若是隻是遍歷建議用each。 二11、判斷一個對象是否爲數組 function isArray(obj){ return Object.prototype.toString.call(obj) == "[object Array]"; } 不能用instanceof 和 constructor來判斷,緣由參考:http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ 二12、經過原型繼承建立一個新對象 function inherit(p){ if(!p){ throw TypeError("p is not an object or null"); } if(Object.create){ return Object.create(p); } var t=typeof p; if(t !== "object" && t !== "function"){ throw TypeError("p is not an object or null"); } function f(){}; f.prototype=p; return new f(); }
原創來自:http://www.cnblogs.com/jscode/archive/2012/07/25/2605395.htmlphp