前端常用功能函数集锦

前端常用功能函数集锦。收集起来,快速开发。

1,parseTime() 格式化时间函数,后端返回时间戳,前端显示年月日,时分秒

export function parseTime(time, cFormat) {
if (arguments.length === 0 || time === null) {
return null
}
const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
let date
if (typeof time === 'object') {
date = time
} else {
if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
time = parseInt(time)
}
if ((typeof time === 'number') && (time.toString().length === 10)) {
time = time * 1000
}
date = new Date(time)
}
const formatObj = {
y: date.getFullYear(),
m: date.getMonth() + 1,
d: date.getDate(),
h: date.getHours(),
i: date.getMinutes(),
s: date.getSeconds(),
a: date.getDay()
}
const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
let value = formatObj[key]
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
if (result.length > 0 && value < 10) {
value = '0' + value
}
return value || 0
})
return time_str
}

2,formatTime() 函数,用于显示距离某一时间点,后多少分钟。

export function formatTime(time, option) {
if (('' + time).length === 10) {
time = parseInt(time) * 1000
} else {
time = +time
}
const d = new Date(time)
const now = Date.now()

const diff = (now - d) / 1000

if (diff < 30) {
return '刚刚'
} else if (diff < 3600) {
// less 1 hour
return Math.ceil(diff / 60) + '分钟前'
} else if (diff < 3600 * 24) {
return Math.ceil(diff / 3600) + '小时前'
} else if (diff < 3600 * 24 * 2) {
return '1天前'
}
if (option) {
return parseTime(time, option)
} else {
return (
d.getMonth() +
1 +
'月' +
d.getDate() +
'日' +
d.getHours() +
'时' +
d.getMinutes() +
'分'
)
}
}

3,getQueryObject() 用户获取url后面的参数

export function getQueryObject(url) {
url = url == null ? window.location.href : url
const search = url.substring(url.lastIndexOf('?') + 1)
const obj = {}
const reg = /([?&=]+)=([?&=]*)/g
search.replace(reg, (rs, 2) => {
const name = decodeURIComponent(2)
val = String(val)
obj[name] = val
return rs
})
return obj
}
用法
const url = 'www.baidu.com?from=baidu'
const params = getQueryObject().from // console.log(parmas) == baidu

export const getRequest = () => {
var url = window.location.href
var theRequest = {}
if (url.indexOf('?') !== -1) {
var str = url.split('?')[1]
var strs = str.split('&')
for (var i = 0; i < strs.length; i++) {
if (theRequest[strs[i].split('=')[0]] == null) {
theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1])
}
}
} else {
var apkArr = url.split('/')
var apk_name = apkArr[apkArr.length - 1]
theRequest = { 'apk': apk_name }
}
return theRequest
}

4,debounce()函数 节流

export function debounce(func, wait, immediate) {
let timeout, args, context, timestamp, result

const later = function() {
// 据上一次触发时间间隔
const last = +new Date() - timestamp

// 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
if (last < wait && last > 0) {
  timeout = setTimeout(later, wait - last)
} else {
  timeout = null
  // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
  if (!immediate) {
    result = func.apply(context, args)
    if (!timeout) context = args = null
  }
}

}

return function(...args) {
context = this
timestamp = +new Date()
const callNow = immediate && !timeout
// 如果延时不存在,重新设定延时
if (!timeout) timeout = setTimeout(later, wait)
if (callNow) {
result = func.apply(context, args)
context = args = null
}

return result

}
}
5, deepClone() 深拷贝

export function deepClone(source) {
if (!source && typeof source !== 'object') {
throw new Error('error arguments', 'deepClone')
}
const targetObj = source.constructor === Array ? [] : {}
Object.keys(source).forEach(keys => {
if (source[keys] && typeof source[keys] === 'object') {
targetObj[keys] = deepClone(source[keys])
} else {
targetObj[keys] = source[keys]
}
})
return targetObj
}

6,uniqueArr() 数组去重

/**

  • @param {Array} arr
  • @returns {Array}
    */
    export function uniqueArr(arr) {
    return Array.from(new Set(arr))
    }

7,createUniqueString()创建唯一的字符串

export function createUniqueString() {
const timestamp = +new Date() + ''
const randomNum = parseInt((1 + Math.random()) * 65536) + ''
return (+(randomNum + timestamp)).toString(32)
}

8,hasClass()某个元素是否有某个类名

export function hasClass(ele, cls) {
return !!ele.className.match(new RegExp('(\s|^)' + cls + '(\s|$)'))
}
9,addClass()增加类名 removeClass()删除类名

export function addClass(ele, cls) {
if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

export function removeClass(ele, cls) {
if (hasClass(ele, cls)) {
const reg = new RegExp('(\s|^)' + cls + '(\s|$)')
ele.className = ele.className.replace(reg, '')
}
}
10,toTop()回到顶部

export function toTop() {
if (document.documentElement && document.documentElement.scrollTop) {
document.documentElement.scrollTop = 0
} else {
document.body.scrollTop = 0
}
}

11, 移动端判断设备类型

export function isIPhone() {
var u = navigator.userAgent
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
var isIPhone = /iPad|iPhone|iPod/.test(navigator.userAgent)

if (isIPhone) {
return 1
} else if (isAndroid) {
return 0
}
}
12,countTime()倒计时每秒变化一次00天00时00分00秒

export function countTime(time) {
const days = Math.floor(time / (60 * 60 * 24)) // 计算天数
let hours = Math.floor(time / (60 * 60) % 24) // 计算小时数
let mins = Math.floor(time / (60) % 60) // 计算分钟数
let seconds = Math.floor(time / 1 % 60) // 计算秒数
if (hours < 10) {
hours = '0' + hours
}
if (mins < 10) {
mins = '0' + mins
}
if (seconds < 10) {
seconds = '0' + seconds
}
return {
days,
hours,
mins,
seconds
}
}
13, 前端生成uuid

export function uuid(len, radix) {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
}
return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
}
14, 浏览器打开一个空白页面,访问url路径

export function goPage(shortURL) {
const open = window.open('about:blank')
const url = shortURL
if (open === null || typeof (open) === 'undefined') {
window.location.href = url
return
}
setTimeout(() => {
open.location = url
}, 1000)
}
15,日期转化成时间

export function dateToTime(str) {
if (!str) {
return 0
} else {
str = str.replace(/-/g, '/') // 将-替换成/,因为下面这个构造函数只支持/分隔的日期字符串
const date = new Date(str)
return date.getTime()
}
}
16, pc端判断电脑类型

export function OSnow() {
let str = ''
var agent = navigator.userAgent.toLowerCase()
var isMac = /macintosh|mac os x/i.test(navigator.userAgent)
if (agent.indexOf('win32') >= 0 || agent.indexOf('wow32') >= 0) {
str = 'win32'
}
if (agent.indexOf('win64') >= 0 || agent.indexOf('wow64') >= 0) {
str = 'win64'
}
if (isMac) {
str = 'mac'
}
return str
}

17,将base64转换成blob

export function dataURLtoFile(dataURI) {
const arr = dataURI.split(',')
const mime = arr[0].match(/:(.*?);/)[1]
const bstr = atob(arr[1])
let n = bstr.length
const u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new Blob([u8arr], { type: mime })
}

18,文本中有换行符,在html则换行

export function huanhang(myString) {
return myString.replace(/(\r\n|\n)/gm, '
')
}
19,将 ArrayBuffer 转换成 String

export function decodeUtf8(arrayBuffer) {
var result = ''
var i = 0
var c = 0
var c2 = 0
var c3 = 0

var data = new Uint8Array(arrayBuffer)

// If we have a BOM skip it
if (data.length >= 3 && data[0] === 0xef && data[1] === 0xbb && data[2] === 0xbf) {
i = 3
}

while (i < data.length) {
c = data[i]

if (c < 128) {
  result += String.fromCharCode(c)
  i++
} else if (c > 191 && c < 224) {
  if (i + 1 >= data.length) {
    throw new Error('UTF-8 Decode failed. Two byte character was truncated.')
  }
  c2 = data[i + 1]
  result += String.fromCharCode(((c & 31) << 6) | (c2 & 63))
  i += 2
} else {
  if (i + 2 >= data.length) {
    throw new Error('UTF-8 Decode failed. Multi byte character was truncated.')
  }
  c2 = data[i + 1]
  c3 = data[i + 2]
  result += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))
  i += 3
}

}
return result
}
20, 对象去重

export function ObjUnique(obj) {
const unique = {}
obj.forEach(function(gpa) {
unique[JSON.stringify(gpa)] = gpa
})
return Object.keys(unique).map(function(u) {
return JSON.parse(u)
})
}

21, 将File文件转成base64

export function fileToBase64(file) {
return window.URL.createObjectURL(file)
}

此21个功能函数,非常好用,可以集成项目中,用到时直接引用,方便开发。拿走不谢。如果你有收集 好用的函数,欢迎留言评论,或者后台回复。发出来,供大家学习参考。

热爱开源。乐于分享!

欢迎关注公众号【程序员蜗牛】

你可能感兴趣的:(前端常用功能函数集锦)