一、類型判斷segmentfault
判斷 Target 的類型,單單用 typeof 並沒有法徹底知足,這其實並非 bug,本質緣由是 JS 的萬物皆對象的理論。所以要真正完美判斷時,咱們須要區分對待:app
很穩的判斷封裝:iphone
let class2type = {} 'Array Date RegExp Object Error'.split(' ').forEach(e => class2type[ '[object ' + e + ']' ] = e.toLowerCase()) function type(obj) { if (obj == null) return String(obj) return typeof obj === 'object' ? class2type[ Object.prototype.toString.call(obj) ] || 'object' : typeof obj }
二、防抖和節流
摘自https://segmentfault.com/a/11...優化
function debounce(fn, wait, immediate) { let timer = null return function() { let args = arguments let context = this if (immediate && !timer) { fn.apply(context, args) } if (timer) clearTimeout(timer) timer = setTimeout(() => { fn.apply(context, args) }, wait) } }
function throttle(fn, wait, immediate) { let timer = null let callNow = true return function() { let context = this, args = arguments if (callNow) { fn.apply(context, args) callNow = false } if (!timer) { timer = setTimeout(() => { fn.apply(context, args) timer = null }, wait) } } }
三、獲取URL參數this
function getUrlKey(name){ return encodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+g,'%20')) || null; }
四、全局尺寸設置
說明:經常使用長度單位px、em、rem。其中px是物理像素,固定大小,無自適應特色;em是相對單位,以父元素大小爲基準倍率,但累計疊乘,容易出錯;rem相對單位,以根元素大小爲基準倍率(document.documentElement.style.fontSize),不疊加,可實現準確自適應。prototype
;(function(win,doc){ function setRem(){ //以iphone6爲標準,按屏幕大小實現屏幕基礎尺寸縮放,16px是文檔的默認尺寸(即1rem默認爲16px),爲方便計算可變動爲50或者100(對應1rem=50px或者100px) doc.documentElement.style.fontSize = 16 * doc.documentElement.clientWidth / 375 + 'px'; } setRem(); //監聽resize事件,屏幕大小發生變化時,隨時變換基礎尺寸 win.addEventListener('resize',function(){ setRem(); },false); })(window,document)
五、深拷貝數據
應用類型(array、object)按引用使用,不能複製,想要複製(深拷貝)須要新建對象,把目標的對象的屬性逐個拷貝。code
function copyArr (arr){ return arr.map((e) => { if(typeof e ==='object'){ return Object.assign({},e) }else { return e } }) }