1.string,number類型轉換的快捷方法javascript
// @param s爲字符串,n爲數字 function fn(obj){ //轉換爲String類型 var s = obj +""; //轉換爲number類型 var n = +obj; }
分享一個面試例子:html
//加會將其後面自動轉換成字符串 "64"+4="644" //減會將其自動轉換成數字 "64"-4=60
2.bool類型轉換java
!!obj,將其強制轉換爲bool類型node
alert(!!0) //結果爲false alert(!!"33dd") //結果爲true
!obj,取相反的bool類型jquery
alert(!0) //結果爲true alert(!"222333") //結果爲false
3.=== 與 ==區別web
=== 是嚴格相等,不會進行類型轉換,而 == 是不嚴格相等,會進行類型轉換。有些js的書中,建議開發人員永遠不要用 == 或者 != 。面試
可是jquery源碼中,有用到「==」或者「!=」的狀況 —— 判斷 undefined 和 null 的時候(undefined == null爲true)。正則表達式
//這裏的判斷,將obj是null,obj是undefined都排除在外了 if(obj != null){ }
4.檢測obj是否爲window對象算法
//null == window.null爲true function isWindow(obj){ return obj != null && obj == window.obj; }
5.|| 與 && 用法技巧chrome
//例 var aa=5; name = aa || {} ; alert(name) 則name爲55 this.name = name || {} //若是name值存在,則值爲name,反之爲{} //例 var aa=5; name = aa && {} ; alert(name) 則name爲{},由於aa爲5,不爲0則爲真 this.name = bool && [] //若是bool爲true,則值爲[],反之則爲bool
經典實例:
( window.foo || ( window.foo = "bar" ) ); alert(window.foo); //彈出 bar
// 爲何最後的結果是bar呢,其實能夠當作是 undefined || bar 出來的結果確定是bar
6.setTimeout(fn,0)與setTimeout(fn)區別(此處有問題,沒有考慮單線程的問題,請比較瞭解的大神,幫忙指點)
setTimeout(fn,0)與setTimeout(fn)都是延遲執行,可是setTimeout(fn)比setTimeout(fn,0)延遲時間還要長,例
function fn(){ var data = new Date(); for(var i=0;i<=1000;i++){ if(i==1000){ console.log("fn="+data.getTime()); } } } function fn1(){ var data = new Date(); for(var i=0;i<=1000;i++){ if(i==1000){ console.log("fn1="+data.getTime()); } } } setTimeout(fn,0), setTimeout(fn1);
結果:
7.判斷是否爲數值
function isNumeric(obj){ return !isNaN(parseFloat(obj)) && isFinite(obj); }
8.判斷是否爲空對象
function isEmptyObject(){ var name; //遍歷不是空對象返回 for (name in obj) { return false; } return true; }
9.檢測對象類型
檢測obj對象類型,返回類型,經過Object.prototype.toString()來判斷類型,可是ie低版本兼容性有問題,所以採用{}.toString來監測,返回爲[object Array],[object Object],[object Function]
// 類型判斷 function isType(type){ return function(o){ return Object.prototype.toString.call(o) === '[object ' + type + ']'; } } var isString = isType(「String」); var isObject = isType("Object"); var isArray = isType("Array"); isString("I'm Barret Lee."); isArray([1,2,3]); isObject({});
10.jquery裏的去除空格trim妙用
//至關於if (String.prototype.trim && 「\uFEFF\xA0″.trim() !== 「」)高級的瀏覽器已經支持原生的String的trim方法,可是pFan還爲了不它無法解析全角空白,因此加多了一個判斷:」\uFEFF\xA0″.trim() !== 「」 vart core_version = "1.0",core_trim = core_version.trim; function trim(){ core_trim && !core_trim.call("\uFEFF\xA0") ? function (text) { return text == null ? "" : core_trim.call(text); //這裏按個人理解應該爲" ".trim.call(text),有點不明白轉換爲"1.1.0".trim.call(text) } : // 高級的瀏覽器已經支持原生的String的trim方法,若是瀏覽器不支持則採用 function (text) { var whitespace = "[\\x20\\t\\r\\n\\f]", rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"); return text == null ? "" : (text + "").replace(rtrim, ""); }, //nodeName函數是獲取dom節點的節點名字或者判斷其名字跟傳入參數是否匹配 nodeName: function(elem,name){ //IE下,DOM節點的nodeName是大寫的,例如DIV return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); } }
11.jquery中檢測數組或者類數組中是否含存在傳入的值
/** 檢查數組中是否存在傳入的值,若是存在就返回值所在的位置,若是不存在就返回-1。 *elem 規定需檢索的值。 *arr 數組 *i 可選的整數參數。規定在數組中開始檢索的位置。它的合法取值是 0 到 arr.length - 1。如省略該參數,則將從數組首元素開始檢索。 */ function inArray(elem, arr, i){ var len; if (arr) { //若是瀏覽器支持Array擁有indexOf方法 if ([].indexOf) { return [].indexOf.call(arr, elem, i); } len = arr.length; //當i爲負數的時候,從數組後邊len+i的位置開始索引 //理解這個分紅兩個部分i = i ? (i < 0 ? Math.max(0, len + i) : i) : 0;,i=i爲true,執行(i < 0 ? Math.max(0, len + i) : i),反正執行i=0 i = i ? i < 0 ? Math.max(0, len + i) : i : 0; for (; i < len; i++) { // 雙重檢測防止相似這樣的數組 ar = [];ar[1]=1;ar[0] = undefined; 0 in ar =false;a[0]===undefined; // 0 in arr => arr[0]是否存在 'nme' in arr => arr['nme']是否存在 if (i in arr && arr[i] === elem) { return i; } } } return -1; }
1.hasOwnProperty()方法
使用hasOwnProperty()方法能夠檢測一個屬性是存在與實例,仍是存在於原型中。這個方法從Object繼承,只在給定屬性存在於對象實例中時,纔會返回true。
function Person(){ this.age=25; this.job="web"; } Person.prototype={ name:'pingfan', sayName:function(){ alert(this.name); } } var person1=new Person(); //來自構造函數,檢測屬性,也返回true alert(person1.hasOwnProperty("age")); //來自原型屬性,返回false alert(person1.hasOwnProperty("name")); person1.name='ping'; //來自實例屬性,返回true alert(person1.hasOwnProperty("name"));
2.經過instanceOf檢查this是否爲構造函數的一個實例
function shiCha(opt){ //檢測this是否爲對象的實例 if( !(this instanceof shiCha)){ return new shiCha(opt); } } var shicha1 = new shiCha(), //會返回一個shiCha對象
shicha2 = shiCha(); //構造函數做爲函數時與其餘函數無心,this指向window
3.javascript中Array.prototype.slice.call(arguments)
咱們一般看到Array.prototype.slice.call(arguments,1)或者Array.prototype.slice.call(arguments),都有點摸不着頭腦,其實咱們就是藉助Array.prototype中slice()將arguments變成一個數組,而且使用該數組工做更方便,第二個參數是從索引值,開始將其變成數組,例Array.prototype.call("22223",2)和Array.prototype.call([1,2,3,4],2),從字符串第二個開始。
function sliArray(array){ //輸出爲從索引1到索引3 return Array.prototype.slice.call(array,1,3); } alert(sliArray([1,2,3,4,5,6])) //結果爲2,3
4.利用閉包,實現單例模式,保證構造函數只實例一次
//對象之間永遠不會徹底相等,除非它們是同一對象,所以即便建立一個具備徹底相同成員的同類對象,它也不會與第一個對象徹底相同
var Universe; (function(){ var instance; Universe = function Universe(){ if(instance){ return instance; } instance = this; //全部功能 this.start_time = 0; this.bang = "Big"; } })() var person1 = new Universe(), person2 = new Universe(); alert(person1 === person2 ); //返回true
5. 利用空對象F,實現對象繼承,效率最高
//利用空對象作媒介,進行繼承效果最佳 function inhert(C,P){ var F=function(){}; F.protototype = P.prototype; C.prototype = new F(); C.prototype.constructor = C; }
6. 構造函數設置return obj對象,會致使對象與原型鏈斷掉
理解這個問題,先理解一個概念,一般咱們用new Object(),其實能夠理解爲隱式的作了三件事情:
①.建立一個空對象,var this ={},繼承object對象的一些原有的屬性;
②.將構造函數寫的屬性掛載到建立的對象,this.name = "pfan";
③.經過new object(),返回this對象
場景一
var Parent = function (){ var that = {}; that.name = "pfan"; that.age = "25"; return that; } Parent.prototype = { contructor:"Parent", sayName:function(){ alert(this.name); }, sayAge:function(){ alert(this.age); } } var child = Parent(), last = new Parent(); console.dir(child); console.dir(last); child.sayName(); last.sayName();
咱們執行打開chrome控制檯,發現經過Parent(),new Parent()方法生成的對象原型鏈都斷裂了。
場景二:咱們把對象的屬性掛載在this上,也達不到想要的結果,構造函數以下:
var Parent = function (){ var that = {}; this.name = "pfan"; this.age = "25"; return that; }
chrome控制檯結果:
場景三:咱們更大膽一點,直接讓that成一個對象,返回that,觀察new Parent(),出來的對象,是否擁有prototype上的方法
var Parent = function (){ this.name = "pfan"; this.age = "25"; var that = {name:"pfan111",age:"2511"} return that; }
chrome控制檯,能夠看到new Parent(),實例返回的對象構造函數設置的返回對象,沒有繼承原型的prototype方法
思考??:若是構造函數返回Array,null,經過new 實例會出現什麼狀況呢?
1.Array,返回了一個Array對象,沒法繼承prototype的原型
2.null結果是返回繼承原型鏈的對象
場景四:構造函數中不返回對象,返回字符串
var Parent = function (){ this.name = "pfan"; this.age = "25"; return "11111"; }
chrome控制檯:發現出來的結果,繼承了原型鏈
經過以上四個場景,咱們得出結論:
1.構造函數裏面,咱們設置return 返回對象或者數組,經過new實例時,會致使原型鏈斷裂
2.構造函數裏面,咱們設置return 返回字符串或者null,或者alert(),經過new實例時,會直接忽略
1. 常見的數組操做方法
數組去重:
//數組去重原型 Array.prototype.unqie = function(){ var arr = this, len=this.length, obj={}, newArr=[]; while(len--){ if(obj[ arr[len] ] !== arr[len]){ obj[arr[len]] = arr[len]; newArr.push( arr[len]); } } return newArr.reverse(); }
//也能夠經過變量來記錄匹配,效率更高
Array.prototype.unique = function(){
var arr = this,poxy,i = arr.length,newArr=[];
while(i--){
if(poxy != arr[i]){
poxy = arr[i];
newArr.push(arr[i]);
}
}
return newArr.reverse();
}
取數組中最大值:
Array.prototype.arrMax=function(){ var arr=this, len=this.length,max=arr[0]; for(var i=1;i<len;i++){ if(max<arr[i]){ max=arr[i]; } } return max; } //數組中經過sort取最大值 Array.prototype.arrMax=function(){ var arr=this; arr.sort(function(a,b){ return a-b; }) return arr[arr.length-1]; } //利用Math.max取數組最大值 Array.prototype.arrMax =function(){ var array = this; return Math.max.apply(null, array); } alert([1,2,3,4,5,6,9,8,7,9].arrMax());
取數組中最小值:
//數組中最的小值 Array.prototype.arrMin=function(){ var arr=this, len=this.length,min=arr[0]; for(var i=1;i<len;i++){ if(min>arr[i]){ min=arr[i]; } } return min; } //數組中經過sort取最的小值 Array.prototype.arrSortMin=function(){ var arr=this; arr.sort(function(a,b){ return a-b; }) return arr[0]; } //利用Math.max取數組最大值 Array.prototype.arrSortMin =function(){ var array = this; return Math.min.apply(null, array); } alert([1,2,3,4,5,6,9,8,7,9].arrSortMin());
複製數組:
Array.prototype.copy = function() { return [].concat(this); };
去除數組中只指定元素,只能去除一個,若是想多個,以前先用unique處理:
Array.prototype.remove = function(value){ for(var i=0,len=this.length;i<len;i++) { if(this[i]==value){ this.splice(i, 1); break; } } return this; }
判斷數組中元素出現的次數最多的一個元素和次數:
Array.prototype.maxNum = function(){ var arr = this,obj={}; for(var i =0, len=arr.length;i<len;i++){ var key = arr[i]; if( ! obj[key]){ obj[key] = 1; }else{ obj[key]++; } } var max = -1,maxStr; for( key in obj){ if(obj[key]>max){ max = obj[key]; maxStr = key; } } //alert(maxStr); maxStr爲最大的元素,max爲次數 return [maxStr,max]; }
2.操做document.loaction的方法集(這裏借用了園友總結的相關方法)
pFan.url = { //#URL //參數:變量名,url爲空則表從當前頁面的url中取 getQuery: function (name, url) { var u = arguments[1] || window.location.search , reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)") , r = u.substr(u.indexOf("?") + 1).match(reg) ; return r != null ? r[2] : ""; } , getHash: function (name, url) { //# 獲取 hash值 var u = arguments[1] || location.hash; var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = u.substr(u.indexOf("#") + 1).match(reg); if (r != null) { return r[2]; } return ""; } , parse: function (url) { //# 解析URL var a = document.createElement('a'); url = url || document.location.href; a.href = url; return { source: url , protocol: a.protocol.replace(':', '') , host: a.hostname , port: a.port , query: a.search , file: (a.pathname.match(/([^\/?#]+)$/i) || [, ''])[1] , hash: a.hash.replace('#', '') , path: a.pathname.replace(/^([^\/])/, '/$1') , relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1] , segments: a.pathname.replace(/^\//, '').split('/') }; } };
3.經常使用的正則表達式
pFan.regExp = { //# 字符串匹配 //是否爲 數字!整數,浮點數 isNum: function (num) { //# 是否爲數組 return !isNaN(num); } , isEmail: function (mail) {//# 是否爲 郵箱 return /^([a-z0-9]+[_\-\.]?)*[a-z0-9]+@([a-z0-9]+[_\-\.]?)*[a-z0-9]+\.[a-z]{2,5}$/i.test(mail); } , isIdCard: function (card) { //# 是否爲 身份證 return /^(\d{14}|\d{17})(\d|[xX])$/.test(card); } , isMobile: function (mobile) { //# 是否爲 手機 return /^0*1\d{10}$/.test(mobile); } , isQQ: function (qq) { //# 是否爲 QQ return /^[1-9]\d{4,10}$/.test(qq); } , isTel: function (tel) { //# 是否爲 電話 return /^\d{3,4}-\d{7,8}(-\d{1,6})?$/.text(tel); } , isUrl: function (url) { //# 是否爲 URL return /https?:\/\/[a-z0-9\.\-]{1,255}\.[0-9a-z\-]{1,255}/i.test(url); } , isColor: function (color) { //# 是否爲 16進制顏色 return /#([\da-f]{3}){1,2}$/i.test(color); } //@id : 身份證 , // @now : 當前時間 如:new Date('2013/12/12') , '2013/12/12' // @age : 容許的年齡 , isAdult: function (id, allowAge, now) { //# 是否年齡是否成年 var age = 0 // 用戶 年月日 , nowDate = 0 //當前年月日 ; allowAge = parseFloat(allowAge) || 18; now = typeof now == 'string' ? new Date(now) : (now || new Date()); if (!this.isIdCard(id)) { return false; } //15位身份證 if (15 == id.length) { age = '19' + id.slice(6, 6); } else { age = id.slice(6, 14); } // 類型轉換 整型 age = ~~age; nowDate = ~~(Tydic.date.format('YYYYMMDD', now)); //比較年齡 if (nowDate - age < allowAge * 1e4) { return false; } return true; } //浮點數 , isFloat: function (num) { //# 是否爲 浮點數 return /^(([1-9]\d*)|(\d+\.\d+)|0)$/.test(num); } //正整數 , isInt: function (num) { //# 是否爲 正整數 return /^[1-9]\d*$/.test(num); } //是否全爲漢字 , isChinese: function (str) { //# 是否全爲 漢字 return /^([\u4E00-\u9FA5]|[\uFE30-\uFFA0])+$/gi.test(str); } };
4.操做className的方法集
PFan.conClass = { hasClass:function(){ return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); }, addClass:function(){ if (!hasClass(ele,cls)) ele.className += " "+cls; }, removeClass:function(){ if (hasClass(ele,cls)) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); ele.className=ele.className.replace(reg,' '); } } }
5.操做字符串方法
pFan.string = { //# 字符串 codeHtml: function (content) { //# 轉義 HTML 字符 return this.replace(content, { '&': "&" , '"': """ , "'": ''' , '<': "<" , '>': ">" , ' ': " " , '\t': "	" , '(': "(" , ')': ")" , '*': "*" , '+': "+" , ',': "," , '-': "-" , '.': "." , '/': "/" , '?': "?" , '\\': "\" , '\n': "<br>" }); } //重複字符串 , repeat: function (word, length, end) { //# 重複字符串 end = end || ''; //加在末位 length = ~~length; return new Array(length * 1 + 1).join(word) + '' + end; } //增長前綴 , addPre: function (pre, word, size) { //# 補齊。如給數字前 加 0 pre = pre || '0'; size = parseInt(size) || 0; word = String(word || ''); var length = Math.max(0, size - word.length); return this.repeat(pre, length, word); } //去除兩邊空格 , trim: function (text) { //# 去除兩邊空格 return (text || '').replace(/^\s+|\s$/, ''); } //去除左邊空格 ,ltrim:function(){ return s.replace( /^(\s*| *)/, ""); } //去除右邊空格 ,rtrim:function(){ return s.replace( /(\s*| *)$/, ""); } //返回腳本內容 ,evalscript:function(s) { if(s.indexOf('<script') == -1) return s; var p = /<script[^\>]*?>([^\x00]*?)<\/script>/ig; var arr = []; while(arr = p.exec(s)) { var p1 = /<script[^\>]*?src=\"([^\>]*?)\"[^\>]*?(reload=\"1\")?(?:charset=\"([\w\-]+?)\")?><\/script>/i; var arr1 = []; arr1 = p1.exec(arr[0]); if(arr1) { appendscript(arr1[1], '', arr1[2], arr1[3]); } else { p1 = /<script(.*?)>([^\x00]+?)<\/script>/i; arr1 = p1.exec(arr[0]); appendscript('', arr1[2], arr1[1].indexOf('reload=') != -1); } } return s; } //清除腳本內容 ,stripscript:function(){ return s.replace(/<script.*?>.*?<\/script>/ig, ''); } //字符串替換 , replace: function (str, re) { //# 字符串替換 str = str || ''; for (var key in re) { replace(key, re[key]); }; function replace(a, b) { var arr = str.split(a); str = arr.join(b); }; return str; } , xss: function (str, type) { //# XSS 轉義 //空過濾 if (!str) { return str === 0 ? "0" : ""; } switch (type) { case "html": //過濾html字符串中的XSS return str.replace(/[&'"<>\/\\\-\x00-\x09\x0b-\x0c\x1f\x80-\xff]/g, function (r) { return "&#" + r.charCodeAt(0) + ";" }).replace(/ /g, " ").replace(/\r\n/g, "<br />").replace(/\n/g, "<br />").replace(/\r/g, "<br />"); break; case "htmlEp": //過濾DOM節點屬性中的XSS return str.replace(/[&'"<>\/\\\-\x00-\x1f\x80-\xff]/g, function (r) { return "&#" + r.charCodeAt(0) + ";" }); break; case "url": //過濾url return escape(str).replace(/\+/g, "%2B"); break; case "miniUrl": return str.replace(/%/g, "%25"); break; case "script": return str.replace(/[\\"']/g, function (r) { return "\\" + r; }).replace(/%/g, "\\x25").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\x01/g, "\\x01"); break; case "reg": return str.replace(/[\\\^\$\*\+\?\{\}\.\(\)\[\]]/g, function (a) { return "\\" + a; }); break; default: return escape(str).replace(/[&'"<>\/\\\-\x00-\x09\x0b-\x0c\x1f\x80-\xff]/g, function (r) { return "&#" + r.charCodeAt(0) + ";" }).replace(/ /g, " ").replace(/\r\n/g, "<br />").replace(/\n/g, "<br />").replace(/\r/g, "<br />"); break; } } // badword , 過濾敏感詞 //@text : 要過濾的文本 , 類型 :字符串 //@words : 敏感詞 ,類型,數組, 如 : ['你妹', '我丟' ,'我靠'] // 若是 用 正則匹配, text 長度 100萬,words 100萬,須要 4秒! , badWord: function (text, words) { //# 敏感詞過濾 text = String(text || ''); words = words || []; var reg = new RegExp(words.join('|'), 'g') , _self = this; return text.replace(reg, function ($0) { var length = String($0 || '').length; return _self.repeat('*', length); }); } };
6.加密方法集
pFan.encrypt = { //# 加密 md5: function (words) { //# md5 哈希算法 /* * Crypto-JS 3.1.2 * http://code.google.com/p/crypto-js */ var CryptoJS = function (s, p) { var m = {}, l = m.lib = {}, n = function () { }, r = l.Base = { extend: function (b) { n.prototype = this; var h = new n; b && h.mixIn(b); h.hasOwnProperty("init") || (h.init = function () { h.$super.init.apply(this, arguments) }); h.init.prototype = h; h.$super = this; return h }, create: function () { var b = this.extend(); b.init.apply(b, arguments); return b }, init: function () { }, mixIn: function (b) { for (var h in b) b.hasOwnProperty(h) && (this[h] = b[h]); b.hasOwnProperty("toString") && (this.toString = b.toString) }, clone: function () { return this.init.prototype.extend(this) } }, q = l.WordArray = r.extend({ init: function (b, h) { b = this.words = b || []; this.sigBytes = h != p ? h : 4 * b.length }, toString: function (b) { return (b || t).stringify(this) }, concat: function (b) { var h = this.words, a = b.words, j = this.sigBytes; b = b.sigBytes; this.clamp(); if (j % 4) for (var g = 0; g < b; g++) h[j + g >>> 2] |= (a[g >>> 2] >>> 24 - 8 * (g % 4) & 255) << 24 - 8 * ((j + g) % 4); else if (65535 < a.length) for (g = 0; g < b; g += 4) h[j + g >>> 2] = a[g >>> 2]; else h.push.apply(h, a); this.sigBytes += b; return this }, clamp: function () { var b = this.words, h = this.sigBytes; b[h >>> 2] &= 4294967295 << 32 - 8 * (h % 4); b.length = s.ceil(h / 4) }, clone: function () { var b = r.clone.call(this); b.words = this.words.slice(0); return b }, random: function (b) { for (var h = [], a = 0; a < b; a += 4) h.push(4294967296 * s.random() | 0); return new q.init(h, b) } }), v = m.enc = {}, t = v.Hex = { stringify: function (b) { var a = b.words; b = b.sigBytes; for (var g = [], j = 0; j < b; j++) { var k = a[j >>> 2] >>> 24 - 8 * (j % 4) & 255; g.push((k >>> 4).toString(16)); g.push((k & 15).toString(16)) } return g.join("") }, parse: function (b) { for (var a = b.length, g = [], j = 0; j < a; j += 2) g[j >>> 3] |= parseInt(b.substr(j, 2), 16) << 24 - 4 * (j % 8); return new q.init(g, a / 2) } }, a = v.Latin1 = { stringify: function (b) { var a = b.words; b = b.sigBytes; for (var g = [], j = 0; j < b; j++) g.push(String.fromCharCode(a[j >>> 2] >>> 24 - 8 * (j % 4) & 255)); return g.join("") }, parse: function (b) { for (var a = b.length, g = [], j = 0; j < a; j++) g[j >>> 2] |= (b.charCodeAt(j) & 255) << 24 - 8 * (j % 4); return new q.init(g, a) } }, u = v.Utf8 = { stringify: function (b) { try { return decodeURIComponent(escape(a.stringify(b))) } catch (g) { throw Error("Malformed UTF-8 data"); } }, parse: function (b) { return a.parse(unescape(encodeURIComponent(b))) } }, g = l.BufferedBlockAlgorithm = r.extend({ reset: function () { this._data = new q.init; this._nDataBytes = 0 }, _append: function (b) { "string" == typeof b && (b = u.parse(b)); this._data.concat(b); this._nDataBytes += b.sigBytes }, _process: function (b) { var a = this._data, g = a.words, j = a.sigBytes, k = this.blockSize, m = j / (4 * k), m = b ? s.ceil(m) : s.max((m | 0) - this._minBufferSize, 0); b = m * k; j = s.min(4 * b, j); if (b) { for (var l = 0; l < b; l += k) this._doProcessBlock(g, l); l = g.splice(0, b); a.sigBytes -= j } return new q.init(l, j) }, clone: function () { var b = r.clone.call(this); b._data = this._data.clone(); return b }, _minBufferSize: 0 }); l.Hasher = g.extend({ cfg: r.extend(), init: function (b) { this.cfg = this.cfg.extend(b); this.reset() }, reset: function () { g.reset.call(this); this._doReset() }, update: function (b) { this._append(b); this._process(); return this }, finalize: function (b) { b && this._append(b); return this._doFinalize() }, blockSize: 16, _createHelper: function (b) { return function (a, g) { return (new b.init(g)).finalize(a) } }, _createHmacHelper: function (b) { return function (a, g) { return (new k.HMAC.init(b, g)).finalize(a) } } }); var k = m.algo = {}; return m }(Math); (function (s) { function p(a, k, b, h, l, j, m) { a = a + (k & b | ~k & h) + l + m; return (a << j | a >>> 32 - j) + k } function m(a, k, b, h, l, j, m) { a = a + (k & h | b & ~h) + l + m; return (a << j | a >>> 32 - j) + k } function l(a, k, b, h, l, j, m) { a = a + (k ^ b ^ h) + l + m; return (a << j | a >>> 32 - j) + k } function n(a, k, b, h, l, j, m) { a = a + (b ^ (k | ~h)) + l + m; return (a << j | a >>> 32 - j) + k } for (var r = CryptoJS, q = r.lib, v = q.WordArray, t = q.Hasher, q = r.algo, a = [], u = 0; 64 > u; u++) a[u] = 4294967296 * s.abs(s.sin(u + 1)) | 0; q = q.MD5 = t.extend({ _doReset: function () { this._hash = new v.init([1732584193, 4023233417, 2562383102, 271733878]) }, _doProcessBlock: function (g, k) { for (var b = 0; 16 > b; b++) { var h = k + b, w = g[h]; g[h] = (w << 8 | w >>> 24) & 16711935 | (w << 24 | w >>> 8) & 4278255360 } var b = this._hash.words, h = g[k + 0], w = g[k + 1], j = g[k + 2], q = g[k + 3], r = g[k + 4], s = g[k + 5], t = g[k + 6], u = g[k + 7], v = g[k + 8], x = g[k + 9], y = g[k + 10], z = g[k + 11], A = g[k + 12], B = g[k + 13], C = g[k + 14], D = g[k + 15], c = b[0], d = b[1], e = b[2], f = b[3], c = p(c, d, e, f, h, 7, a[0]), f = p(f, c, d, e, w, 12, a[1]), e = p(e, f, c, d, j, 17, a[2]), d = p(d, e, f, c, q, 22, a[3]), c = p(c, d, e, f, r, 7, a[4]), f = p(f, c, d, e, s, 12, a[5]), e = p(e, f, c, d, t, 17, a[6]), d = p(d, e, f, c, u, 22, a[7]), c = p(c, d, e, f, v, 7, a[8]), f = p(f, c, d, e, x, 12, a[9]), e = p(e, f, c, d, y, 17, a[10]), d = p(d, e, f, c, z, 22, a[11]), c = p(c, d, e, f, A, 7, a[12]), f = p(f, c, d, e, B, 12, a[13]), e = p(e, f, c, d, C, 17, a[14]), d = p(d, e, f, c, D, 22, a[15]), c = m(c, d, e, f, w, 5, a[16]), f = m(f, c, d, e, t, 9, a[17]), e = m(e, f, c, d, z, 14, a[18]), d = m(d, e, f, c, h, 20, a[19]), c = m(c, d, e, f, s, 5, a[20]), f = m(f, c, d, e, y, 9, a[21]), e = m(e, f, c, d, D, 14, a[22]), d = m(d, e, f, c, r, 20, a[23]), c = m(c, d, e, f, x, 5, a[24]), f = m(f, c, d, e, C, 9, a[25]), e = m(e, f, c, d, q, 14, a[26]), d = m(d, e, f, c, v, 20, a[27]), c = m(c, d, e, f, B, 5, a[28]), f = m(f, c, d, e, j, 9, a[29]), e = m(e, f, c, d, u, 14, a[30]), d = m(d, e, f, c, A, 20, a[31]), c = l(c, d, e, f, s, 4, a[32]), f = l(f, c, d, e, v, 11, a[33]), e = l(e, f, c, d, z, 16, a[34]), d = l(d, e, f, c, C, 23, a[35]), c = l(c, d, e, f, w, 4, a[36]), f = l(f, c, d, e, r, 11, a[37]), e = l(e, f, c, d, u, 16, a[38]), d = l(d, e, f, c, y, 23, a[39]), c = l(c, d, e, f, B, 4, a[40]), f = l(f, c, d, e, h, 11, a[41]), e = l(e, f, c, d, q, 16, a[42]), d = l(d, e, f, c, t, 23, a[43]), c = l(c, d, e, f, x, 4, a[44]), f = l(f, c, d, e, A, 11, a[45]), e = l(e, f, c, d, D, 16, a[46]), d = l(d, e, f, c, j, 23, a[47]), c = n(c, d, e, f, h, 6, a[48]), f = n(f, c, d, e, u, 10, a[49]), e = n(e, f, c, d, C, 15, a[50]), d = n(d, e, f, c, s, 21, a[51]), c = n(c, d, e, f, A, 6, a[52]), f = n(f, c, d, e, q, 10, a[53]), e = n(e, f, c, d, y, 15, a[54]), d = n(d, e, f, c, w, 21, a[55]), c = n(c, d, e, f, v, 6, a[56]), f = n(f, c, d, e, D, 10, a[57]), e = n(e, f, c, d, t, 15, a[58]), d = n(d, e, f, c, B, 21, a[59]), c = n(c, d, e, f, r, 6, a[60]), f = n(f, c, d, e, z, 10, a[61]), e = n(e, f, c, d, j, 15, a[62]), d = n(d, e, f, c, x, 21, a[63]); b[0] = b[0] + c | 0; b[1] = b[1] + d | 0; b[2] = b[2] + e | 0; b[3] = b[3] + f | 0 }, _doFinalize: function () { var a = this._data, k = a.words, b = 8 * this._nDataBytes, h = 8 * a.sigBytes; k[h >>> 5] |= 128 << 24 - h % 32; var l = s.floor(b / 4294967296); k[(h + 64 >>> 9 << 4) + 15] = (l << 8 | l >>> 24) & 16711935 | (l << 24 | l >>> 8) & 4278255360; k[(h + 64 >>> 9 << 4) + 14] = (b << 8 | b >>> 24) & 16711935 | (b << 24 | b >>> 8) & 4278255360; a.sigBytes = 4 * (k.length + 1); this._process(); a = this._hash; k = a.words; for (b = 0; 4 > b; b++) h = k[b], k[b] = (h << 8 | h >>> 24) & 16711935 | (h << 24 | h >>> 8) & 4278255360; return a }, clone: function () { var a = t.clone.call(this); a._hash = this._hash.clone(); return a } }); r.MD5 = t._createHelper(q); r.HmacMD5 = t._createHmacHelper(q) })(Math); return CryptoJS.MD5(words).toString(); } // sha1 , sha1: function (words) { //# sha1 哈希算法 var CryptoJS = function (e, m) { var p = {}, j = p.lib = {}, l = function () { }, f = j.Base = { extend: function (a) { l.prototype = this; var c = new l; a && c.mixIn(a); c.hasOwnProperty("init") || (c.init = function () { c.$super.init.apply(this, arguments) }); c.init.prototype = c; c.$super = this; return c }, create: function () { var a = this.extend(); a.init.apply(a, arguments); return a }, init: function () { }, mixIn: function (a) { for (var c in a) a.hasOwnProperty(c) && (this[c] = a[c]); a.hasOwnProperty("toString") && (this.toString = a.toString) }, clone: function () { return this.init.prototype.extend(this) } }, n = j.WordArray = f.extend({ init: function (a, c) { a = this.words = a || []; this.sigBytes = c != m ? c : 4 * a.length }, toString: function (a) { return (a || h).stringify(this) }, concat: function (a) { var c = this.words, q = a.words, d = this.sigBytes; a = a.sigBytes; this.clamp(); if (d % 4) for (var b = 0; b < a; b++) c[d + b >>> 2] |= (q[b >>> 2] >>> 24 - 8 * (b % 4) & 255) << 24 - 8 * ((d + b) % 4); else if (65535 < q.length) for (b = 0; b < a; b += 4) c[d + b >>> 2] = q[b >>> 2]; else c.push.apply(c, q); this.sigBytes += a; return this }, clamp: function () { var a = this.words, c = this.sigBytes; a[c >>> 2] &= 4294967295 << 32 - 8 * (c % 4); a.length = e.ceil(c / 4) }, clone: function () { var a = f.clone.call(this); a.words = this.words.slice(0); return a }, random: function (a) { for (var c = [], b = 0; b < a; b += 4) c.push(4294967296 * e.random() | 0); return new n.init(c, a) } }), b = p.enc = {}, h = b.Hex = { stringify: function (a) { var c = a.words; a = a.sigBytes; for (var b = [], d = 0; d < a; d++) { var f = c[d >>> 2] >>> 24 - 8 * (d % 4) & 255; b.push((f >>> 4).toString(16)); b.push((f & 15).toString(16)) } return b.join("") }, parse: function (a) { for (var c = a.length, b = [], d = 0; d < c; d += 2) b[d >>> 3] |= parseInt(a.substr(d, 2), 16) << 24 - 4 * (d % 8); return new n.init(b, c / 2) } }, g = b.Latin1 = { stringify: function (a) { var c = a.words; a = a.sigBytes; for (var b = [], d = 0; d < a; d++) b.push(String.fromCharCode(c[d >>> 2] >>> 24 - 8 * (d % 4) & 255)); return b.join("") }, parse: function (a) { for (var c = a.length, b = [], d = 0; d < c; d++) b[d >>> 2] |= (a.charCodeAt(d) & 255) << 24 - 8 * (d % 4); return new n.init(b, c) } }, r = b.Utf8 = { stringify: function (a) { try { return decodeURIComponent(escape(g.stringify(a))) } catch (c) { throw Error("Malformed UTF-8 data"); } }, parse: function (a) { return g.parse(unescape(encodeURIComponent(a))) } }, k = j.BufferedBlockAlgorithm = f.extend({ reset: function () { this._data = new n.init; this._nDataBytes = 0 }, _append: function (a) { "string" == typeof a && (a = r.parse(a)); this._data.concat(a); this._nDataBytes += a.sigBytes }, _process: function (a) { var c = this._data, b = c.words, d = c.sigBytes, f = this.blockSize, h = d / (4 * f), h = a ? e.ceil(h) : e.max((h | 0) - this._minBufferSize, 0); a = h * f; d = e.min(4 * a, d); if (a) { for (var g = 0; g < a; g += f) this._doProcessBlock(b, g); g = b.splice(0, a); c.sigBytes -= d } return new n.init(g, d) }, clone: function () { var a = f.clone.call(this); a._data = this._data.clone(); return a }, _minBufferSize: 0 }); j.Hasher = k.extend({ cfg: f.extend(), init: function (a) { this.cfg = this.cfg.extend(a); this.reset() }, reset: function () { k.reset.call(this); this._doReset() }, update: function (a) { this._append(a); this._process(); return this }, finalize: function (a) { a && this._append(a); return this._doFinalize() }, blockSize: 16, _createHelper: function (a) { return function (c, b) { return (new a.init(b)).finalize(c) } }, _createHmacHelper: function (a) { return function (b, f) { return (new s.HMAC.init(a, f)).finalize(b) } } }); var s = p.algo = {}; return p }(Math); (function () { var e = CryptoJS, m = e.lib, p = m.WordArray, j = m.Hasher, l = [], m = e.algo.SHA1 = j.extend({ _doReset: function () { this._hash = new p.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]) }, _doProcessBlock: function (f, n) { for (var b = this._hash.words, h = b[0], g = b[1], e = b[2], k = b[3], j = b[4], a = 0; 80 > a; a++) { if (16 > a) l[a] = f[n + a] | 0; else { var c = l[a - 3] ^ l[a - 8] ^ l[a - 14] ^ l[a - 16]; l[a] = c << 1 | c >>> 31 } c = (h << 5 | h >>> 27) + j + l[a]; c = 20 > a ? c + ((g & e | ~g & k) + 1518500249) : 40 > a ? c + ((g ^ e ^ k) + 1859775393) : 60 > a ? c + ((g & e | g & k | e & k) - 1894007588) : c + ((g ^ e ^ k) - 899497514); j = k; k = e; e = g << 30 | g >>> 2; g = h; h = c } b[0] = b[0] + h | 0; b[1] = b[1] + g | 0; b[2] = b[2] + e | 0; b[3] = b[3] + k | 0; b[4] = b[4] + j | 0 }, _doFinalize: function () { var f = this._data, e = f.words, b = 8 * this._nDataBytes, h = 8 * f.sigBytes; e[h >>> 5] |= 128 << 24 - h % 32; e[(h + 64 >>> 9 << 4) + 14] = Math.floor(b / 4294967296); e[(h + 64 >>> 9 << 4) + 15] = b; f.sigBytes = 4 * e.length; this._process(); return this._hash }, clone: function () { var e = j.clone.call(this); e._hash = this._hash.clone(); return e } }); e.SHA1 = j._createHelper(m); e.HmacSHA1 = j._createHmacHelper(m) })(); return CryptoJS.SHA1(words).toString(); } // time33 哈希 , time33: function (words) { //# time33 哈希算法 words = words || ''; //哈希time33算法 for (var i = 0, len = words.length, hash = 5381; i < len; ++i) { hash += (hash << 5) + words.charAt(i).charCodeAt(); }; return hash & 0x7fffffff; } }
7.日期方法集
pFan.date = { //返回時間戳 getTimeStamp:function(){ var timestamp=new Date().getTime(); return timestamp.toString(); }, //時間戳轉爲日期格式 //@nS爲時間戳 getLocalTime: function(nS) { return new Date(parseInt(nS) * 1000).toLocaleString().substr(0,17); }, //@time , 時間 , 如 new Date('2013/11/10 0:12:12') //@pre , 星期的 前綴,如:周 ,星期 //@ nums ,如:一二三四五六日 getWeek: function (time, pre, nums) { //# 獲取星期幾 time = typeof time == 'string' ? this.parse(time) : (time || new Date()); pre = pre || '星期'; //周 nums = nums || '日一二三四五六'; return pre + nums[time.getDay()]; }, //@formatType : YYYY, YY, MM //@ time : new Date('2013/11/12') //@weeks : 日一二三四五六 format: function (formatType, time, weeks) { //格式化輸出時間 var pre = '0', formatType = formatType || 'YYYY-MM-DD', weeks = weeks || '日一二三四五六', time = time || new Date(); //格式化時間 return (formatType || '') .replace(/yyyy|YYYY/g, time.getFullYear()) .replace(/yy|YY/g, Tydic.string.addPre(pre, time.getFullYear() % 100), 2) .replace(/mm|MM/g, Tydic.string.addPre(pre, time.getMonth() + 1, 2)) .replace(/m|M/g, time.getMonth() + 1) .replace(/dd|DD/g, Tydic.string.addPre(pre, time.getDate(), 2)) .replace(/d|D/g, time.getDate()) .replace(/hh|HH/g, Tydic.string.addPre(pre, time.getHours(), 2)) .replace(/h|H/g, time.getHours()) .replace(/ii|II/g, Tydic.string.addPre(pre, time.getMinutes(), 2)) .replace(/i|I/g, time.getMinutes()) .replace(/ss|SS/g, Tydic.string.addPre(pre, time.getSeconds(), 2)) .replace(/s|S/g, time.getSeconds()) .replace(/w/g, time.getDay()) .replace(/W/g, weeks[time.getDay()]); } }
1.遞歸方法實現以下數列:1,1,2,3,5,8,13,21,34,55……
//a爲位數 a爲大於1的正整數 function diGui(a){ if(a<=2){ return 1; }else{ return arguments.callee(a-1)+arguments.callee(a-2); } } alert(diGui(31));
2.百度產生時間戳的方法
new Date()/36e5
3.獲取字符串字節,一個由於字母1個字節,一箇中文字符2個字節
//字節 function getBite(str){ var len = str.length,i=len; while(i--){ //中文字符串的charCodeAt碼大於255 if(strrr[i].charCodeAt()>255)len++; } return len; } alert(getBite(strrr));
4.var聲明提早的問題
var aa = 123; function alaa(){ alert(aa) //結果爲undefined var aa = "111"; //這裏的聲明被提早的,可是賦值在後 alert(aa); //結果爲111 } alaa();
等價於:
var aa; alert(aa); aa=111; alert(aa);
5.操做數組的問題
var arr = [1,2,3,4,5,6]; var newArr = arr; arr.splice(0,3); console.log(newArr); //彈出結果爲[4,5,6]
newArr = arr,這一步其實咱們像造成一種拷貝的形式,但是到咱們去刪除arr數組裏面的而原始,發現newArr裏面的元素也減小了,因此newArr = arr,只是將newArr的數組指針指向了arr,因此操做arr時影響newArr。
解決辦法:
var arr = [1,2,3,4,5,6]; var newArr = arr.slice(0); arr.splice(0,3),arr.push("111"); console.log(arr); //結果[4,5,6,"111"] console.log(newArr); //結果 [1,2,3,4,5,6]
6.隨機打亂數組
function shuffle(array) { return array.sort(function() { return Math.random() - 0.5 }); }
參考文字打亂數組順序:http://www.cnblogs.com/wayou/p/fisher_yates_shuffle.html