時間戳:css
獲取時間戳的方法: 1、(new Date("2017/04/14")).valueOf() 2、Date.parse(new Date("2017/04/14")) 3、new Date("2017/04/14").getTime() 4、+new Date("2017/04/14") 時間戳對比: new Date('2016/09/03')的時間爲:2016-09-03 new Date(2016, 9, 3)的時間爲:2016-10-03,加了一個月
判斷:html
if(result){ console.log('aaaa') }; 可寫成: result&&console.log('aaaa') if(!result){ console.log('aaaa') }; 可寫成: result||console.log('aaaa')
條件選擇:jquery
if(result=="yes"){ a="111"; }else{ a="000"; } 可寫成: a=result=="yes"?"111":"000";
去除數組中的undefind:json
var a=[2,5,undefind,6,8,undefined,9]; var b=[]; for(var i=0;i<a.length;i++){ if(a[i]!=undefined){ b.push(a[i]) } }; 可寫成: var a=[2,5,undefind,6,8,undefined,9]; a=a.filter(function(){ return true; })
把數組中值的空隔換成其餘:數組
var data=[2009/10/18 6:00', '2009/10/18 7:00', '2009/10/18 8:00'] data.map(function (str) {return str.replace(' ', '\n') }); console.log(data)
判斷元素是否在數組中:dom
var a=[48,56,65,77,6,80,92]; for(var i in a){ if(i===6){ console.log("包含6"); } }; 可寫成: var a=[48,56,65,77,6,80,92]; a.indexOf(6)>-1 && console.log("包含6");
return布爾值時:spa
(function (){ if (age > 18) { return true; } else { return false; } })(); 可寫成 (function (){ return age > 18; })();
if不嵌套if:code
if (user.id === 10) { if (user.name !== "") { if (user.email === "email") { //do something... } } } 可寫成: if(user.id === 10 && user.name !=="" && user.email === "email") { //do something... }
固定範圍內的取值,超出取 最大值|最小值:htm
(function(){ var a=120; if(a>100){ a=100; }else if(a<0){ a=0; } alert(a); }()); 可寫成: (function(){ var a=120; a=Math.min(100,Math.max(a,0)); alert(a); }())
取指定範圍內的隨機數:blog
Math.random()*(min-max)+max
jquery 建立div的方法:
$('<div>',{ id:'ddd', class:'bbb', css:{width:'300px',height:'200px',backgroundColor:'#333'} })
tab形式的iframe:
<table cellpadding="0" cellspacing="0"> <tr> <td><a href="a.html" target="fx">aaa</a></td> <td><a href="b.html" target="fx">bbb</a></td> </tr> </table> <iframe name="fx" id="fx" src="a.html" width="100px" frameborder="0" scrolling="no"></iframe>
防止被Iframe嵌套:
if(top != self){ location.href = 」about:blank」; }
用json替換switch:
(function(){ var a=1,b; switch(a) { case 1: b='蘋果'; break; case 2: b='桔子'; break; case 3: b='香蕉'; break; case 4: b='梨子'; break; } console.log(b) }()) ==> (function(){ var obj={1:'蘋果',2:'桔子',3:'香蕉',4:'梨子'},a=4; console.log(obj[a]) }())
json排序
var grades = [ { "name": "張三", "grade": 95 }, { "name": "李四", "grade": 62 }, { "name": "王五", "grade": 86 } ]; grades.sort(function(a, b) { return a.grade - b.grade })
禁用右鍵菜單:
$(document).ready(function(){ $(document).bind("contextmenu",function(e){ return false; }); });