一、类型判断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 } }) }