前端实用小工具

2次阅读

共计 1305 个字符,预计需要花费 4 分钟才能阅读完成。

1、类型判断
判断 Target 的类型,单单用 typeof 并无法完全满足,这其实并不是 bug,本质原因是 JS 的万物皆对象的理论。因此要真正完美判断时,我们需要区分对待:

基本类型(null): 使用 String(null)
基本类型(string / number / boolean /undefined) + function: 直接使用 typeof 即可
其余引用类型 (Array / Date / RegExp Error): 调用 toString 后根据[object XXX] 进行判断

很稳的判断封装:
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、防抖和节流摘自 https://segmentfault.com/a/11…
防抖 (debounce): 将多次高频操作优化为只在最后一次执行,通常使用的场景是:用户输入,只需再输入完成后做一次输入校验即可。
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): 每隔一段时间后执行一次,也就是降低频率,将高频操作优化成低频操作,通常使用场景: 滚动条事件 或者 resize 事件,通常每隔 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、获取 URL 参数
function getUrlKey(name){
return encodeURIComponent((new RegExp(‘[?|&]’ + name + ‘=’ + ‘([^&;]+?)(&|#|;|$)’).exec(location.href)||[,””])[1].replace(/\+g,’%20′)) || null;
}

正文完
 0