在前端开发中,往往我们需要使用各种工具函数
判断是数组类型
es6版本
isArray = (arg) => Array.isArray(arg)
早期版本
isArray = (arg) => Object.prototype.toString.call(arg).indexOf('Array') > 0
判断是对象
es6版本
isPlainObject = (arg) => Object.prototype.toString.call(arg) === '[object Object]'
判断NAN
isNan(arg)
判断NULL
isNull = (arg) => {
if (typeof arg === 'object' && arg === null) {
return true
}
return false
}
深复制
function copy (orgin) {
let target , i
if (isPlainObject(orgin)) {
target = {}
for (i in orgin) {
if (!target.hasOwnProperty(i) || isArray(orgin[i])) {
if (isPlainObject(orgin[i])) {
target[i] = copy(orgin[i])
} else {
target[i] = orgin[i]
}
}
}
} else if (isArray(orgin)) {
target = []
for( i = 0; i < orgin.length; i++) {
if (isPlainObject(orgin[i]) || isArray(orgin[i])) {
target.push(copy(orgin[i]))
} else {
target[i] = orgin[i]
}
}
}
return target
}
数组的递归复制
function clone(arg) {
if (isArray(arg)) {
return arg.map(clone)
}
}
节流函数
保证一段时间里只执行一次
function throttle(...args) {
let now = Date.now()
let time = args[0]
let wait = args[2]
let fn = args[1]
let that = this
let timer
return function () {
let st = Date.now()
clearTimeout(timer)
if (st - now >= time) {
now = st
arg = Array.prototype.slice(3)
fn.call(that, arg)
} else {
timer = setTimeout(fn, wait)
}
}
}
防抖函数
每次操作合并成一次操作
function Shake (...args) {
var timer
var time = args[0]
var fn = args[1]
return function () {
clearTimeout(timer)
timer = setTimeout(fn, time)
}
}
判断是否支持touch事件
function isSupportTouch (){
return ('ontouchstart' in window) || window.DocumentTouch && document instanceof window.DocumentTouch;
}
网友评论