一、取URL中的参数
function getParameterByName(name) { var match = RegExp('[?&]' + name + '=([^&]*)') .exec(window.location.search); return match && decodeURIComponent(match[1].replace(/\+/g, ' ')); }
二、正则分组
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"] */
三、为什么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。
四、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')
五、jQuery中判断一个元素是否存在
if ($(selector).length)
六、用JavaScript对URL进行编码
var myUrl = "http://example.com/index.html?param=1&anotherParam=2"; var myOtherUrl = "http://example.com/index.html?url=" + encodeURIComponent(myUrl);
七、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。
八、JavaScript检查一个字符串是否为空最简单的方法
if (strValue) { //do something }
九、用JavaScript添加和删除class
//Add Class document.getElementById("MyElement").className += " MyClass"; //Remove Class document.getElementById("MyElement").className = document.getElementById("MyElement").className.replace(/(?:^|\s)MyClass(?!\S)/,'');
十、在jQuery中取消一个ajax请求
var xhr = $.ajax({ type: "POST", url: "test.php", data: "name=test", success: function(msg){ alert( msg ); } }); //取消请求 xhr.abort()
要注意的是,在ajax请求未响应之前可以用xhr.abort()取消,但如果请求已经到达了服务器端,这样做的结果仅仅是让浏览器不再监听这个请求的响应,但服务器端仍然会进行处理。
十一、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,一个是真正的删除了。
十二、JavaScript中16进制与10进制相互转换
var sHex=(255).toString(16);//ff var iNum=parseInt("ff",16);//255
十三、JavaScript多行字符串
如何在JavaScript中方便地写一个多行字符串呢,有三种方案,你自己选吧:
//one var testHtml="a"+ "b"+ "c"; //two var testHtml2="a\ b\ c"; //three var testHtml3=["a", "b", "c"].join("");
十四、JavaScript中!!操作符是什么
console.log(!!10);//true console.log(!!0);//false console.log(!!"abc");//true console.log(!!"");//false
简单地说就是把右侧的值转为bool值
十五、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; }
十六、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."); }
十七、JavaScript字符与ASCII码间的转换
console.log("\n".charCodeAt(0));//10 console.log(String.fromCharCode(65));//A
十八、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
十九、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
二十、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。
一、JavaScript跨平台事件
对于跨平台事件我们一般这么写(只例举添加事件):
function addEventHandler(oTarget, sEventType, fnHandler){ if(oTarget.addEventListener){ oTarget.addEventListener(sEventType,fnHandler,false); } else if(oTarget.attachEvent){ oTarget.attachEvent("on"+sEventType,fnHandler); } else{ oTarget["on"+sEventType]=fnHandler; } }
那么下面这段代码的效果是什么样的呢?
<div id="test">Test</div> ... var oDiv=document.getElementById("test"); addEventHandler(oDiv,"mouseover",function(){ alert("over "+this.id); });
由于IE的this问题,在IE中果断地弹出了 over undefined,所以跨平台的事件更好的写法是这样的:
function addEventHandler(oTarget, sEventType, fnHandler){ if(oTarget.addEventListener){ oTarget.addEventListener(sEventType,fnHandler,false); } else if(oTarget.attachEvent){ oTarget.attachEvent("on"+sEventType,function(){ return fnHandler.call(oTarget,window.event); }); } else{ oTarget["on"+sEventType]=fnHandler; } }
二、合并两个Array并去掉重复项
Array.prototype.unique = function() { var a = this.concat(); for(var i=0; i<a.length; ++i) { for(var j=i+1; j<a.length; ++j) { if(a[i] === a[j]) a.splice(j, 1); } } return a; }; //Demo var array1 = ["a","b"]; var array2 = ["b", "c"]; var array3 = array1.concat(array2).unique(); // ["a","b","c"]
三、typeof === "undefined" vs. != null
if(typeof neverDeclared == "undefined") //no errors if(neverDeclared == null) //throws ReferenceError: neverDeclared is not defined
so,typeof === "undefined" is better!
四、setTimeout(fn, 0)的意义
浏览器同时要做很多事,这些事情以队列的方式存在,执行JavaScript只是其中之一,setTimeout(fn, 0)表面上看是立即执行的意思,但实际上只是在浏览器事件队列中添加了一个新的事件,由于队列是先进先出,所以fn会等等到当前队列中的事件执行完后再执行。由于JavaScript的定时器回调函数是异步执行的,所以产生的效果就是等页面上同步事件(包括页面渲染与同步JS代码)执行完之后再执行。
一个简单的示例:
<script type="text/javascript"> //one document.getElementById("imgTest").style.borderBottom="5px solid #000"; //two setTimeout(function(){ document.getElementById("imgTest").style.borderBottom="5px solid #000"; }, 0); </script> <img src="http://jscode.chinacxy.com/img_lib/m_400_600_01.jpg" id="imgTest" alt=""/>
one会报错,因为页面执行到这里时还没有img,但two却可以。
五、增强版取URL中的参数
function getQueryString() { var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m; while (m = re.exec(queryString)) { result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); } return result; } // demo var myParam = getQueryString()["myParam"];
六、检查一个object是否是jQuery object
if(obj instanceof jQuery)
七、检查一个数是否为整数或浮点数
function isInt(n) { return typeof n === 'number' && n % 1 == 0; } // or ,this support ie3 function isInt(n) { return typeof n === 'number' && parseFloat(n) == parseInt(n, 10) && !isNaN(n); } function isFloat (n) { return n===+n && n!==(n|0); }
八、用JavaScript添加style节点
var css = 'h1 { background: red; }', head = document.getElementsByTagName('head')[0], style = document.createElement('style'); style.type = 'text/css'; if(style.styleSheet){ style.styleSheet.cssText = css; }else{ style.appendChild(document.createTextNode(css)); } head.appendChild(style);
九、如何跳出双重循环
function foo () { dance: for(var k = 0; k < 4; k++){ for(var m = 0; m < 4; m++){ if(m == 2){ break dance; } } } }
十、把一个Array追加到另一个Array上
var a=[1,2],b=[3,4,5]; a.push.apply(a,b); /*a: [1, 2, 3, 4, 5]*/
十一、用jQuery把页面上的一个tag换成另一个tag
如把页面上所有的code换为pre:
<code> A </code> <code> B </code> <code> C </code> //change to <pre> A </pre> <pre> A </pre> <pre> A </pre>
jQuery代码:
$('code').contents().unwrap().wrap('<pre/>'); //or $('code').replaceWith(function(){ return $("<pre />").append($(this).contents()); });
十二、取数组中的最小值和最大值
var arr = new Array(); arr[0] = 100; arr[1] = 0; arr[2] = 50; var min = Math.min.apply(null, arr), max = Math.max.apply(null, arr);
十三、取两个数组交集
/* finds the intersection of * two arrays in a simple fashion. * * PARAMS * a - first array, must already be sorted * b - second array, must already be sorted * * NOTES * * Should have O(n) operations, where n is * n = MIN(a.length(), b.length()) */ function arrayIntersection(a, b) { var ai=0, bi=0; var result = new Array(); while( ai < a.length && bi < b.length ) { if (a[ai] < b[bi] ){ ai++; } else if (a[ai] > b[bi] ){ bi++; } else /* they're equal */ { result.push(a[ai]); ai++; bi++; } } return result; } console.log(arrayIntersection([1,2,3],[2,3,4,5,6]));//[2,3]
注释中已经说明了,传入的数组要已经排过序的。
十四、统计一个字符串中某段子串出现的次数
var temp = "This is a string."; var count = temp.match(/is/g).length;
十五、方法返回多个值
//One var mValues= function(){ var a ="a"; var b = "b"; return [a, b]; }; var values= mValues(); var valOne= values[0]; var valTwo = values[1]; //Two var mValues= function(){ var a= "a"; var b = "b"; return { 'a': a, 'b': b }; }; var values= mValues(); var valOne= values.a; var valTwo = values.b;
十六、Array迭代器
function createIterator(x) { var i = 0; return function(){ return x[i++]; }; } var iterator=createIterator(['a','b','c','d','e','f','g']); var current; while(current=iterator()) { console.log(current); }
注意,如果数组中有0、false、""、null、NaN迭代器将会停止。
十七、根据日计算年龄
function getAge(dateString) { var today = new Date(); var birthDate = new Date(dateString); var age = today.getFullYear() - birthDate.getFullYear(); var m = today.getMonth() - birthDate.getMonth(); if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) { age--; } return age; }
console.log(getAge("2005,8,1"));//6
十八、判断当前页面是否被放入了iframe中
if(self==top){ //not in iframe }else{ //in iframe }
这段代码可以用来防止网页被放入iframe中,不过如果别人定义了self和top变量覆盖了浏览器默认值可能会失效。
十九、把arguments转换为Array
var args = Array.prototype.slice.call(arguments, 0);
二十、日期格式化
来源:javascript日期格式化函数,跟C#中的使用方法类似
Date.prototype.toString=function(format,loc){ var time={}; time.Year=this.getFullYear(); time.TYear=(""+time.Year).substr(2); time.Month=this.getMonth()+1; time.TMonth=time.Month<10?"0"+time.Month:time.Month; time.Day=this.getDate(); time.TDay=time.Day<10?"0"+time.Day:time.Day; time.Hour=this.getHours(); time.THour=time.Hour<10?"0"+time.Hour:time.Hour; time.hour=time.Hour<13?time.Hour:time.Hour-12; time.Thour=time.hour<10?"0"+time.hour:time.hour; time.Minute=this.getMinutes(); time.TMinute=time.Minute<10?"0"+time.Minute:time.Minute; time.Second=this.getSeconds(); time.TSecond=time.Second<10?"0"+time.Second:time.Second; time.Millisecond=this.getMilliseconds(); time.Week=this.getDay(); var MMMArrEn=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]; var MMMArr=["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]; var WeekArrEn=["Sun","Mon","Tue","Web","Thu","Fri","Sat"]; var WeekArr=["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]; var oNumber=time.Millisecond/1000; if(format!=undefined && format.replace(/\s/g,"").length>0){ if(loc!=undefined && loc =="en"){ MMMArr=MMMArrEn.slice(0); WeekArr=WeekArrEn.slice(0); } format=format .replace(/yyyy/ig,time.Year) .replace(/yyy/ig,time.Year) .replace(/yy/ig,time.TYear) .replace(/y/ig,time.TYear) .replace(/MMM/g,MMMArr[time.Month-1]) .replace(/MM/g,time.TMonth) .replace(/M/g,time.Month) .replace(/dd/ig,time.TDay) .replace(/d/ig,time.Day) .replace(/HH/g,time.THour) .replace(/H/g,time.Hour) .replace(/hh/g,time.Thour) .replace(/h/g,time.hour) .replace(/mm/g,time.TMinute) .replace(/m/g,time.Minute) .replace(/ss/ig,time.TSecond) .replace(/s/ig,time.Second) .replace(/fff/ig,time.Millisecond) .replace(/ff/ig,oNumber.toFixed(2)*100) .replace(/f/ig,oNumber.toFixed(1)*10) .replace(/EEE/g,WeekArr[time.Week]); } else{ format=time.Year+"-"+time.Month+"-"+time.Day+" "+time.Hour+":"+time.Minute+":"+time.Second; } return format; } var d=new Date(); console.log(d.toString()); //2012-7-27 9:26:52 console.log(d.toString("")); //2012-7-27 9:26:52 console.log(d.toString("yyyy-MM-dd HH:mm:ss")); //2012-07-27 09:26:52 console.log(d.toString("yyyy年MM月dd日 HH:mm:ss")); //2012年07月27日 09:26:52 console.log(d.toString("yyyy-MM-dd HH:mm:ss fff")); //2012-07-27 09:26:52 237 console.log(d.toString("yyyy年 MMM dd EEE")); //2012年 七月 27 星期五 console.log(d.toString("yyyy MMM dd EEE","en")); //2012 Jul 27 Fri