JavaScript常用的工具函数,不全面大家补充哦
目录
博主介绍
💂 个人主页:苏州程序大白
💂 个人社区:CSDN全国各地程序猿
🤟作者介绍:中国DBA联盟(ACDU)成员,CSDN全国各地程序猿(媛)聚集地管理员。目前从事工业自动化软件开发工作。擅长C#、Java、机器视觉、底层算法等语言。2019年成立柒月软件工作室。
💬如果文章对你有帮助,欢迎关注、点赞、收藏(一键三连)和C#、Halcon、python+opencv、VUE、各大公司面试等一些订阅专栏哦
🎗? 承接软件APP、小程序、网站等开发重点行业应用开发(SaaS、PaaS、CRM、HCM、银行核心系统、监管报送平台、系统搭建、人工智能助理)、大数据平台开发、商业智能、App开发、ERP、云平台、智能终端、产品化解决方案。测试软件产品测试、应用软件测试、测试平台及产品、测试解决方案。运维数据库维护(SQL Server 、Oracle、MySQL)、 操作系统维护(Windows、Linux、Unix等常用系统)、 服务器硬件设备维护、网络设备维护、 运维管理平台等。运营服务IT咨询 、IT服务、业务流程外包(BPO)、云/基础设施的管理、线上营销、数据采集与标注、内容管理和营销、设计服务、本地化、智能客服、大数据分析等。
💅 有任何问题欢迎私信,看到会及时回复
👤 微信号:stbsl6,微信公众号:苏州程序大白
🎯 想加入技术交流群的可以加我好友,群里会分享学习资料
JavaScript
JavaScript ( JS ) 是一种具有函数优先的轻量级,解释型或即时编译型的编程语言。虽然它是作为开发Web 页面的脚本语言而出名的,但是它也被用到了很多非浏览器环境中等等。
格式化时间戳
export function formatDateTimeStamp(date, fmt) {
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
}
let o = {
'M+': date.getMonth() + 1,
'd+': date.getDate(),
'h+': date.getHours(),
'm+': date.getMinutes(),
's+': date.getSeconds()
}
for (let k in o) {
if (new RegExp(`(${k})`).test(fmt)) {
let str = o[k] + ''
fmt = fmt.replace(
RegExp.$1, (RegExp.$1.length === 1) ?
str :
padLeftZero(str))
}
}
return fmt
}
function padLeftZero(str) {
return ('00' + str).substr(str.length);
}
export function parseTime(time, cFormat) {
if (arguments.length === 0) {
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(/{([ymdhisa])+}/g, (result, key) => {
const value = formatObj[key]
if (key === 'a') {
return ['日', '一', '二', '三', '四', '五', '六'][value]
}
return value.toString().padStart(2, '0')
})
return time_str
}
时间格式化 几分钟前 几小时前
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) {
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() +
'分'
)
}
}
function pluralize(time, label) {
if (time === 1) {
return time + label + ' ago'
}
return time + label + 's' + ' ago'
}
export function timeAgo(time) {
const between = Date.now() / 1000 - Number(time)
if (between < 3600) {
return pluralize(~~(between / 60), ' minute')
} else if (between < 86400) {
return pluralize(~~(between / 3600), ' hour')
} else {
return pluralize(~~(between / 86400), ' day')
}
}
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, $1, $2) => {
const name = decodeURIComponent($1)
let val = decodeURIComponent($2)
val = String(val)
obj[name] = val
return rs
})
return obj
}
export function param2Obj(url) {
const search = url.split('?')[1]
if (!search) {
return {}
}
return JSON.parse(
'{"' +
decodeURIComponent(search)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"')
.replace(/\+/g, ' ') +
'"}'
)
}
对象序列化【对象转url参数】
function cleanArray(actual) {
const newArray = []
for (let i = 0; i < actual.length; i++) {
if (actual[i]) {
newArray.push(actual[i])
}
}
return newArray
}
export function param(obj) {
if (!obj) return ''
return cleanArray(
Object.keys(obj).map(key => {
if (obj[key] === undefined) return ''
return encodeURIComponent(key) + '=' + encodeURIComponent(obj[key])
})
).join('&')
}
export function stringfyQueryStr(obj) {
if (!obj) return '';
let pairs = [];
for (let key in obj) {
let value = obj[key];
if (value instanceof Array) {
for (let i = 0; i < value.length; ++i) {
pairs.push(encodeURIComponent(key + '[' + i + ']') + '=' + encodeURIComponent(value[i]));
}
continue;`在这里插入代码片`
}
pairs.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
return pairs.join('&');
}
param({name:'1111',sex:'wwww'})
stringfyQueryStr({name:'1111',sex:'wwww'})
本地存储
export const store = {
set: function(name, value, day) {
let d = new Date()
let time = 0
day = (typeof(day) === 'undefined' || !day) ? 1 : day
time = d.setHours(d.getHours() + (24 * day))
localStorage.setItem(name, JSON.stringify({
data: value,
time: time
}))
},
get: function(name) {
let data = localStorage.getItem(name)
if (!data) {
return null
}
let obj = JSON.parse(data)
if (new Date().getTime() > obj.time) {
localStorage.removeItem(name)
return null
} else {
return obj.data
}
},
clear: function(name) {
if (name) {
localStorage.removeItem(name)
} else {
localStorage.clear()
}
}
}
cookie操作
export const cookie = {
set: function(name, value, day) {
let oDate = new Date()
oDate.setDate(oDate.getDate() + (day || 30))
document.cookie = name + '=' + value + ';expires=' + oDate + "; path=/;"
},
get: function(name) {
let str = document.cookie
let arr = str.split('; ')
for (let i = 0; i < arr.length; i++) {
let newArr = arr[i].split('=')
if (newArr[0] === name) {
return newArr[1]
}
}
},
del: function(name) {
this.set(name, '', -1)
}
}
数字格式化单位
export function numberFormatter(num, digits)
{
const si = [{
value: 1E18,
symbol: 'E'
},
{
value: 1E15,
symbol: 'P'
},
{
value: 1E12,
symbol: 'T'
},
{
value: 1E9,
symbol: 'G'
},
{
value: 1E6,
symbol: 'M'
},
{
value: 1E3,
symbol: 'k'
}
]
for (let i = 0; i < si.length; i++) {
if (num >= si[i].value) {
return (num / si[i].value).toFixed(digits).replace(/\.0+$|(\.[0-9]*[1-9])0+$/, '$1') + si[i].symbol
}
}
return num.toString()
}
数字千位过滤
export function toThousandFilter(num) {
let targetNum = (num || 0).toString()
if (targetNum.includes('.')) {
let arr = num.split('.')
return arr[0].replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ',')) + '.' + arr[1]
} else {
return targetNum.replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}
}
过滤成版本号
export function versionFilter(versions) {
let v0 = (versions & 0xff000000) >> 24
let v1 = (versions & 0xff0000) >> 16
let v2 = (versions & 0xff00) >> 8
let v3 = versions & 0xff
return `${v0}.${v1}.${v2}.${v3}`
}
首字母大写
export function uppercaseFirst(string) {
return string.charAt(0).toUpperCase() + string.slice(1)
}
class骚操作
export function hasClass(ele, cls) {
return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}
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, ' ')
}
}
文本复制功能
const copyTxt = function(text, fn) {
if (typeof document.execCommand !== 'function') {
console.log('复制失败,请长按复制')
return
}
var dom = document.createElement('textarea')
dom.value = text
dom.setAttribute('style', 'display: block;width: 1px;height: 1px;')
document.body.appendChild(dom)
dom.select()
var result = document.execCommand('copy')
document.body.removeChild(dom)
if (result) {
console.log('复制成功')
typeof fn === 'function' && fn()
return
}
if (typeof document.createRange !== 'function') {
console.log('复制失败,请长按复制')
return
}
var range = document.createRange()
var div = document.createElement('div')
div.innerhtml = text
div.setAttribute('style', 'height: 1px;fontSize: 1px;overflow: hidden;')
document.body.appendChild(div)
range.selectNode(div)
var selection = window.getSelection()
console.log(selection)
if (selection.rangeCount > 0) {
selection.removeAllRanges()
}
selection.addRange(range)
document.execCommand('copy')
typeof fn === 'function' && fn()
console.log('复制成功')
}
判断是否是一个数组
export const castArray = value => (Array.isArray(value) ? value : [value])
export const castArray = arr=> Object.prototype.toString.call(arr) === '[object Array]'
判断是否是一个空数组
export const isEmpty = (arr) => !Array.isArray(arr) || arr.length === 0
克隆一个数组
const clone = (arr) => arr.slice(0);
const clone = (arr) => [...arr];
const clone = (arr) => Array.from(arr);
const clone = (arr) => arr.map((x) => x);
const clone = (arr) => JSON.parse(JSON.stringify(arr));
const clone = (arr) => arr.concat([]);
数组去重
export const uniqueArray = (arr) => Array.from(new Set(arr))
export const uniqueArray = (arr) => arr.filter((el, i, array) => array.indexOf(el) === i)
export const uniqueArray = (arr) => arr.reduce((acc, el) => (acc.includes(el) ? acc : [...acc, el]), [])
是否为PC端
export const isPC = function() {
let userAgentInfo = navigator.userAgent
let Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod']
let flag = true
for (let v = 0; v < Agents.length; v++) {
if (userAgentInfo.indexOf(Agents[v]) > 0) {
flag = false
break
}
}
return flag
}
判断是否为微信
export const isWx = () => {
var ua = window.navigator.userAgent.toLowerCase()
if (ua.match(/MicroMessenger/i) === 'micromessenger') {
return true
}
return false
}
设备判断:android、ios、web
export const isDevice = function() {
var ua = navigator.userAgent.toLowerCase()
if (ua.match(/iPhone\sOS/i) === 'iphone os' || ua.match(/iPad/i) === 'ipad') {
return 'iOS'
}
if (ua.match(/Android/i) === 'android') {
return 'Android'
}
return 'Web'
}
常见正则校验
export const normalReg = (str, type) => {
switch (type) {
case 'phone':
return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str);
case 'tel':
return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str);
case 'card':
return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str);
case 'pwd':
return /^[a-zA-Z]\w{5,17}$/.test(str)
case 'postal':
return /[1-9]\d{5}(?!\d)/.test(str);
case 'QQ':
return /^[1-9][0-9]{4,9}$/.test(str);
case 'email':
return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str);
case 'money':
return /^\d*(?:\.\d{0,2})?$/.test(str);
case 'URL':
return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
case 'IP':
return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str);
case 'date':
return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) || /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
case 'number':
return /^[0-9]$/.test(str);
case 'positiveInteger':
return /^[1-9]\d*$/.test(str);
case 'price':
return /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(str);
case 'english':
return /^[a-zA-Z]+$/.test(str);
case 'chinese':
return /^[\u4E00-\u9FA5]+$/.test(str);
case 'lower':
return /^[a-z]+$/.test(str);
case 'upper':
return /^[A-Z]+$/.test(str);
case 'HTML':
return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str);
default:
return true;
}
}
去除字符串空格
export const trim = function(str, type) {
type = type || 1
switch (type) {
case 1:
return str.replace(/\s+/g, '')
case 2:
return str.replace(/(^\s*)|(\s*$)/g, '')
case 3:
return str.replace(/(^\s*)/g, '')
case 4:
return str.replace(/(\s*$)/g, '')
default:
return str
}
}
过滤html代码
export const filterTag = function(str) {
str = str.replace(/&/ig, '&')
str = str.replace(/</ig, '<')
str = str.replace(/>/ig, '>')
str = str.replace(' ', ' ')
return str
}
生成随机数范围
export const random = function(min, max) {
if (arguments.length === 2) {
return Math.floor(min + Math.random() * ((max + 1) - min))
} else {
return null
}
}
判断图片加载完成
export const imgLoadAll = function(arr, callback) {
let arrImg = []
for (let i = 0; i < arr.length; i++) {
let img = new Image()
img.src = arr[i]
img.onload = function() {
arrImg.push(this)
if (arrImg.length == arr.length) {
callback && callback()
}
}
}
}
光标所在位置插入字符
export const insertAtCursor = function(dom, val) {
if (document.selection) {
dom.focus()
let sel = document.selection.createRange()
sel.text = val
sel.select()
} else if (dom.selectionStart || dom.selectionStart == '0') {
let startPos = dom.selectionStart
let endPos = dom.selectionEnd
let restoreTop = dom.scrollTop
dom.value = dom.value.substring(0, startPos) + val + dom.value.substring(endPos, dom.value.length)
if (restoreTop > 0) {
dom.scrollTop = restoreTop
}
dom.focus()
dom.selectionStart = startPos + val.length
dom.selectionEnd = startPos + val.length
} else {
dom.value += val
dom.focus()
}
}
图片地址转base64
export const getBase64 = function(img) {
let getBase64Image = function(img, width, height) {
let canvas = document.createElement("canvas");
canvas.width = width ? width : img.width;
canvas.height = height ? height : img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
let dataURL = canvas.toDataURL();
return dataURL;
}
let image = new Image();
image.crossOrigin = '';
image.src = img;
let deferred = $.Deferred();
if (img) {
image.onload = function() {
deferred.resolve(getBase64Image(image));
}
return deferred.promise();
}
}
base64图片下载功能
export const downloadFile = (base64, fileName) => {
let base64ToBlob = (code) => {
let parts = code.split(';base64,');
let contentType = parts[0].split(':')[1];
let raw = window.atob(parts[1]);
let rawLength = raw.length;
let uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
};
let aLink = document.createElement('a');
let blob = base64ToBlob(base64);
let evt = document.createEvent("HTMLEvents");
evt.initEvent("click", true, true);
aLink.download = fileName;
aLink.href = URL.createObjectURL(blob);
aLink.click();
}
浏览器是否支持webP格式图片
export const webPBool = () => !![].map &&
document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') == 0
H5软键盘缩回、弹起回调
export function(downCb, upCb) {
var clientHeight = window.innerHeight
downCb = typeof downCb === 'function' ? downCb : function() {}
upCb = typeof upCb === 'function' ? upCb : function() {}
window.addEventListener('resize', () => {
var height = window.innerHeight
if (height === clientHeight) {
downCb()
}
if (height < clientHeight) {
upCb()
}
})
}
对象属性剔除
function omit(object, props=[]){
let res = {}
Object.keys(object).forEach(key=>{
if(props.includes(key) === false){
res[key] = typeof object[key] === 'object' && object[key] !== null ? jsON.parse(jsON.stringify(object[key])) : object[key]
}
})
return res
}
let data = { id: 1, title: '12345', name: '男'}
omit(data, ['id'])
深拷贝
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
}
函数防抖
export function debounce(func, wait, immediate) {
let timeout, args, context, timestamp, result
const later = function() {
const last = +new Date() - timestamp
if (last < wait && last > 0) {
timeout = setTimeout(later, wait - last)
} else {
timeout = null
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
}
}
函数节流
export function(func, wait ,type) {
if(type===1){
let previous = 0;
}else if(type===2){
let timeout;
}
return function() {
let context = this;
let args = arguments;
if(type===1){
let now = Date.now();
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}else if(type===2){
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
}
🌟作者相关的文章、资源分享🌟
🌟让天下没有学不会的技术🌟
学习C#不再是难问题
🌳《C#入门到高级教程》🌳
有关C#实战项目
👉C#RS232C通讯源码👈
👉C#委托数据传输👈
👉C# Modbus TCP 源代码👈
👉C# 仓库管理系统源码👈
👉C# 欧姆龙通讯Demo👈
👉C#+WPF+SQL目前在某市上线的车管所摄像系统👈
👉2021C#与Halcon视觉通用的框架👈
👉2021年视觉项目中利用C#完成三菱PLC与上位机的通讯👈
👉VP联合开源深度学习编程(WPF)👈
?有关C#项目欢迎各位查看个人主页?
🌟机器视觉、深度学习🌟
学习机器视觉、深度学习不再是难问题
🌌《Halcon入门到精通》🌌
🌌《深度学习资料与教程》🌌
有关机器视觉、深度学习实战
👉2021年C#+HALCON视觉软件👈
👉2021年C#+HALCON实现模板匹配👈
👉C#集成Halcon的深度学习软件👈
👉C#集成Halcon的深度学习软件,带[MNIST例子]数据集👈
👉C#支持等比例缩放拖动的halcon WPF开源窗体控件👈
👉2021年Labview联合HALCON👈
👉2021年Labview联合Visionpro👈
👉基于Halcon及VS的动车组制动闸片厚度自动识别模块👈
?有关机器视觉、深度学习实战欢迎各位查看个人主页?
🌟Java、数据库教程与项目🌟
学习Java、数据库教程不再是难问题
🍏《JAVA入门到高级教程》🍏
🍏《数据库入门到高级教程》🍏
有关Java、数据库项目实战
👉Java经典怀旧小霸王网页游戏机源码增强版👈
👉js+css类似网页版网易音乐源码👈
👉Java物业管理系统+小程序源码👈
👉JavaWeb家居电子商城👈
👉JAVA酒店客房预定管理系统的设计与实现SQLserver👈
👉JAVA图书管理系统的研究与开发MYSQL👈
?有关Java、数据库教程与项目实战欢迎各位查看个人主页?
🌟分享Python知识讲解、分享🌟
学习Python不再是难问题
🥝《Python知识、项目专栏》🥝
🥝《Python 检测抖音关注账号是否封号程》🥝
🥝《手把手教你Python+Qt5安装与使用》🥝
🥝《用一万字给小白全面讲解python编程基础问答》🥝
🥝《Python 绘制Android CPU和内存增长曲线》🥝
🥝《??苏州程序大白用万字解析Python网络编程与Web编程??《??记得收藏??》》🥝
有关Python项目实战
👉Python基于Django图书管理系统👈
👉Python管理系统👈
👉2021年9个常用的python爬虫源码👈
👉python二维码生成器👈
?有关Python教程与项目实战欢迎各位查看个人主页?
🌟分享各大公司面试题、面试流程🌟
面试成功不是难事
🍏《2021年金九银十最新的VUE面试题??《??记得收藏??》》🍏
🍏《只要你认真看完一万字??Linux操作系统基础知识??分分钟钟都吊打面试官《??记得收藏??》》🍏
🍏《??用一万字给小白全面讲解python编程基础问答??《😀记得收藏不然看着看着就不见了😀》》🍏
?有关各大公司面试题、面试流程欢迎各位查看个人主页?
💫点击直接资料领取💫
? 这里有各种学习资料还有有有趣好玩的编程项目,更有难寻的各种资源。 ? ?
??关注苏州程序大白公众号??
👇 👇👇
|