js 常用工具函数 校验数据类型/防抖/节流/手机号脱敏/解析url参数/判断手机平台/数组去重/滚动到页面顶部/滚动到元素位置/存储/下载文件/模糊搜索/

// 校验数据类型
export const typeofData = function(obj) {
    
    
	return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}
// typeofData('树哥')  // string
// typeofData([])  // array
// typeofData(new Date())  // date
// typeofData(null) // null
// typeofData(true) // boolean
// typeofData(() => { }) // function

// 防抖
export const debounce = (() => {
    
    
	let timer = null
	return (callback, wait = 800) => {
    
    
		timer && clearTimeout(timer)
		timer = setTimeout(callback, wait)
	}
})
// 如 vue 中使用
// methods: {
    
    
//   loadList() {
    
    
//     debounce(() => {
    
    
//       console.log('加载数据')
//     }, 500)
//   }
// }

// 节流
export const throttle = (() => {
    
    
	let last = 0
	return (callback, wait = 800) => {
    
    
		let now = +new Date()
		if (now - last > wait) {
    
    
			callback()
			last = now
		}
	}
})

// 手机号脱敏
export const hideMobile = (mobile) => {
    
    
	return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2")
}
// hideMobile('13211111111') // '132****1111'

// 解析URL参数
export const getSearchParams = () => {
    
    
	const searchPar = new URLSearchParams(window.location.search)
	const paramsObj = {
    
    }
	for (const [key, value] of searchPar.entries()) {
    
    
		paramsObj[key] = value
	}
	return paramsObj
}
// https://****com/index?id=154513&age=18;
// getSearchParams(); // {id: "154513", age: "18"}

// 判断手机是Andoird还是IOS
export const getOSType = () => {
    
    
	let u = navigator.userAgent,
		app = navigator.appVersion
	let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1
	let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
	if (isIOS) {
    
    
		return 1
	}
	if (isAndroid) {
    
    
		return 2
	}
	return 3
}
// getOSType()

// 数组对象根据字段名去重
export const uniqueArrayObject = (arr = [], key = 'id') => {
    
    
	if (arr.length === 0) return
	let list = []
	const map = {
    
    }
	arr.forEach((item) => {
    
    
		if (!map[item[key]]) {
    
    
			map[item[key]] = item
		}
	})
	list = Object.values(map)
	return list
}
// const responseList = [
//     { id: 1, name: '树哥' },
//     { id: 2, name: '黄老爷' },
//     { id: 3, name: '张麻子' },
//     { id: 1, name: '黄老爷' },
//     { id: 2, name: '张麻子' },
//     { id: 3, name: '树哥' },
//     { id: 1, name: '树哥' },
//     { id: 2, name: '黄老爷' },
//     { id: 3, name: '张麻子' },
// ]
// uniqueArrayObject(responseList, 'id')
// [{ id: 1, name: '树哥' },{ id: 2, name: '黄老爷' },{ id: 3, name: '张麻子' }]

// 滚动到页面顶部
export const scrollTop = () => {
    
    
	const height = document.documentElement.scrollTop || document.body.scrollTop
	if (height > 0) {
    
    
		window.requestAnimationFrame(scrollTop)
		window.scrollTo(0, height - height / 8)
	}
}

// 滚动到元素位置
export const smoothScroll = element => {
    
    
	document.querySelector(element).scrollIntoView({
    
    
		behavior: 'smooth'
	})
}
// smoothScroll('#target'); // 平滑滚动到 ID 为 target 的元素

// uuid
export const uuid = () => {
    
    
	const temp_url = URL.createObjectURL(new Blob())
	const uuid = temp_url.toString()
	URL.revokeObjectURL(temp_url) //释放这个url
	return uuid.substring(uuid.lastIndexOf('/') + 1)
}
// uuid() // a640be34-689f-4b98-be77-e3972f9bffdd
// uuid一般应由后端来进行生成

// 存储操作
class MyCache {
    
    
	constructor(isLocal = true) {
    
    
		this.storage = isLocal ? localStorage : sessionStorage
	}
	setItem(key, value) {
    
    
		if (typeof(value) === 'object') value = JSON.stringify(value)
		this.storage.setItem(key, value)
	}
	getItem(key) {
    
    
		try {
    
    
			return JSON.parse(this.storage.getItem(key))
		} catch (e) {
    
    
			return this.storage.getItem(key)
		}
	}
	removeItem(key) {
    
    
		this.storage.removeItem(key)
	}
	clear() {
    
    
		this.storage.clear()
	}
	key(index) {
    
    
		return this.storage.key(index)
	}
	length() {
    
    
		return this.storage.length
	}
}
const localCache = new MyCache()
const sessionCache = new MyCache(false)
export {
    
    
	localCache,
	sessionCache
}
// localCache.getItem('user')
// sessionCache.setItem('name','树哥')
// sessionCache.getItem('token')
// localCache.clear()

// 下载文件
// 参数:api 接口 params 请求参数 fileName 文件名
const downloadFile = (api, params, fileName, type = 'get') => {
    
    
	axios({
    
    
		method: type,
		url: api,
		responseType: 'blob',
		params: params
	}).then((res) => {
    
    
		let str = res.headers['content-disposition']
		if (!res || !str) {
    
    
			return
		}
		let suffix = ''
		// 截取文件名和文件类型
		if (str.lastIndexOf('.')) {
    
    
			fileName ? '' : decodeURI(str.substring(str.lastIndexOf('=') + 1, str.lastIndexOf('.')))
			suffix = str.substring(str.lastIndexOf('.'), str.length)
		}
		//  如果支持微软的文件下载方式(ie10+浏览器)
		if (window.navigator.msSaveBlob) {
    
    
			try {
    
    
				const blobObject = new Blob([res.data])
				window.navigator.msSaveBlob(blobObject, fileName + suffix)
			} catch (e) {
    
    
				console.log(e);
			}
		} else {
    
    
			//  其他浏览器
			let url = window.URL.createObjectURL(res.data)
			let link = document.createElement('a')
			link.style.display = 'none'
			link.href = url
			link.setAttribute('download', fileName + suffix)
			document.body.appendChild(link)
			link.click()
			document.body.removeChild(link)
			window.URL.revokeObjectURL(link.href)
		}
	}).catch((err) => {
    
    
		console.log(err.message);
	})
}
// downloadFile('/api/download', {id}, '文件名')

// 时间操作:day.js
// Day.js 是一个仅 2kb 大小的轻量级 JavaScript 时间日期处理库,下载、解析和执行的JavaScript更少,为代码留下更多的时间。

// 模糊搜索
// 参数: list 原数组 keyWord 查询的关键词 attribute 数组需要检索属性
export const fuzzyQuery = (list, keyWord, attribute = 'name') => {
    
    
	const reg = new RegExp(keyWord)
	const arr = []
	for (let i = 0; i < list.length; i++) {
    
    
		if (reg.test(list[i][attribute])) {
    
    
			arr.push(list[i])
		}
	}
	return arr
}
// const list = [
//   { id: 1, name: '树哥' },
//   { id: 2, name: '黄老爷' },
//   { id: 3, name: '张麻子' },
//   { id: 4, name: '汤师爷' },
//   { id: 5, name: '胡万' },
//   { id: 6, name: '花姐' },
//   { id: 7, name: '小梅' }
// ]
// fuzzyQuery(list, '树', 'name') // [{id: 1, name: '树哥'}]


// 遍历树节点
export const foreachTree = (data, callback, childrenName = 'children') => {
    
    
	for (let i = 0; i < data.length; i++) {
    
    
		callback(data[i])
		if (data[i][childrenName] && data[i][childrenName].length > 0) {
    
    
			foreachTree(data[i][childrenName], callback, childrenName)
		}
	}
}
// 假设我们要从树状结构数据中查找 id 为 9 的节点
// const treeData = [{
    
    
// 	id: 1,
// 	label: '一级 1',
// 	children: [{
    
    
// 		id: 4,
// 		label: '二级 1-1',
// 		children: [{
    
    
// 			id: 9,
// 			label: '三级 1-1-1'
// 		}, {
    
    
// 			id: 10,
// 			label: '三级 1-1-2'
// 		}]
// 	}]
// }, {
    
    
// 	id: 2,
// 	label: '一级 2',
// 	children: [{
    
    
// 		id: 5,
// 		label: '二级 2-1'
// 	}, {
    
    
// 		id: 6,
// 		label: '二级 2-2'
// 	}]
// }, {
    
    
// 	id: 3,
// 	label: '一级 3',
// 	children: [{
    
    
// 		id: 7,
// 		label: '二级 3-1'
// 	}, {
    
    
// 		id: 8,
// 		label: '二级 3-2'
// 	}]
// }]
// let result
// foreachTree(treeData, (item) => {
    
    
// 	if (item.id === 9) {
    
    
// 		result = item
// 	}
// })
// console.log('result', result) // {id: 9,label: "三级 1-1-1"}

猜你喜欢

转载自blog.csdn.net/qiaoqiaohong/article/details/127449370