[轉(zhuǎn)]Javascript 絕句
像詩一樣的 Javascript 代碼。
1. 取整同時(shí)轉(zhuǎn)成數(shù)值型:
'10.567890'|0 //結(jié)果: 10 '10.567890'^0 //結(jié)果: 10 -2.23456789|0 //結(jié)果: -2 ~~-2.23456789 //結(jié)果: -2
2. 日期轉(zhuǎn)數(shù)值:
var d = +new Date(); //1295698416792
3. 類數(shù)組對(duì)象轉(zhuǎn)數(shù)組:
var arr = [].slice.call(arguments)
4. 漂亮的隨機(jī)碼:
Math.random().toString(16).substring(2); //14位 Math.random().toString(36).substring(2); //11位
5. 合并數(shù)組:
var a = [1,2,3]; var b = [4,5,6]; Array.prototype.push.apply(a, b); uneval(a); //[1,2,3,4,5,6]
6. 用0補(bǔ)全位數(shù):
function prefixInteger(num, length) { return (num / Math.pow(10, length)).toFixed(length).substr(2); }
7. 交換值:
a= [b, b=a][0];
8. 將一個(gè)數(shù)組插入另一個(gè)數(shù)組的指定位置:
var a = [1,2,3,7,8,9]; var b = [4,5,6]; var insertIndex = 3; a.splice.apply(a, Array.concat(insertIndex, 0, b)); // a: 1,2,3,4,5,6,7,8,9
9. 刪除數(shù)組元素:
var a = [1,2,3,4,5]; a.splice(3,1);
10. 快速取數(shù)組最大和最小值
Math.max.apply(Math, [1,2,3]) //3 Math.min.apply(Math, [1,2,3]) //1
(出自http://ejohn.org/blog/fast-javascript-maxmin/)
11. 條件判斷:
var a = b && 1; //相當(dāng)于 if (b) { a = 1; } else { a = b; } var a = b || 1; //相當(dāng)于 if (b) { a = b; } else { a = 1; }
12. 判斷IE(兩種方法):
var ie = /*@cc_on !@*/false; var ie = !-[1,];
原文地址:http://www.benben.cc/blog/?p=391
13. 把函數(shù)參數(shù)轉(zhuǎn)換為數(shù)組:
Array.apply(null,arguments); Array.prototype.slice.call(arguments,0);
14. 一個(gè)數(shù)組中插入另一個(gè)數(shù)組:
var a=[0,1,4],b=[2,3]; [].splice.apply(a, [2,0].concat(b)); //a為 [0,1,2,3,4] //方法二: a.splice.apply(a,[2,0],b);// a為[0,1,2,3,4]

作者:Artwl
本文首發(fā)博客園,版權(quán)歸作者跟博客園共有。轉(zhuǎn)載必須保留本段聲明,并在頁面顯著位置給出本文鏈接,否則保留追究法律責(zé)任的權(quán)利。
浙公網(wǎng)安備 33010602011771號(hào)