1. Type judgment
It is not a bug to judge the type of Target with typeof alone. The essential reason is JS's theory that everything is an object. Therefore, in order to truly perfect judgment, we need to distinguish:
- Basic type (null): use String(null)
- Basic type (string / number / boolean /undefined) + function: use typeof directly
- Other reference types (Array / Date / RegExp Error): judge according to [object XXX] after calling toString
Very stable judgment package:
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 }
2. Anti shake and throttling
Excerpt from https://segmentfault.com/a/11...
- Debounce: optimize multiple high-frequency operations to only be performed at the last time. The common scenario is: user input, only input verification once after input.
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) } }
- Throttle: perform once every other period of time, i.e. reduce the frequency, optimize the high-frequency operation to low-frequency operation, usually using the scenario: scroll bar event or resize event, usually once every 100-500 Ms.
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) } } }
3. Get URL parameters
function getUrlKey(name){ return encodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href)||[,""])[1].replace(/\+g,'%20')) || null; }