1、校验数据类型
export const typeOf = function(obj) {
return Object.prototype.toString.call(obj).slice(8, -1).toLowerCase()
}
//示例代码
typeOf([]) // array
typeOf(null) //null
typeOf(() => {}) //function
2、数组对象根据某一个字段去重
// arr-> 表示要去重数组, key-> 表示要去重的字段
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 list = [
{ 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(list, 'id')
3、滚动到元素位置
export const smoothScroll = element =>{
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
};
//示例
smoothScroll('#target'); // 平滑滚动到 ID 为 target 的元素
4、滚动到页面顶部
export const scrollToTop = () => {
const height = document.documentElement.scrollTop || document.body.scrollTop;
if (height > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, height - height / 8);
}
}
//示例
scrollToTop()
5、金额格式化
export const moneyFormat = (number, decimals, dec_point, thousands_sep) => {
number = (number + '').replace(/[^0-9+-Ee.]/g, '')
const n = !isFinite(+number) ? 0 : +number
const prec = !isFinite(+decimals) ? 2 : Math.abs(decimals)
const sep = typeof thousands_sep === 'undefined' ? ',' : thousands_sep
const dec = typeof dec_point === 'undefined' ? '.' : dec_point
let s = ''
const toFixedFix = function(n, prec) {
const k = Math.pow(10, prec)
return '' + Math.ceil(n * k) / k
}
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.')
const re = /(-?\d+)(\d{3})/
while (re.test(s[0])) {
s[0] = s[0].replace(re, '$1' + sep + '$2')
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || ''
s[1] += new Array(prec - s[1].length + 1).join('0')
}
return s.join(dec)
}
//示例
moneyFormat(10000000) // 10,000,000.00
moneyFormat(10000000, 3, '.', '-') // 10-000-000.000
6、下载文件
// 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 ? '' : fileName = decodeURI(str.substring(str.indexOf('=') + 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}, '文件名')
7、遍历树节点
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)
}
}
}
//示例
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(data, (item) => {
if (item.id === 9) {
result = item
}
})
console.log('result', result) // {id: 9,label: "三级 1-1-1"}
8、对象格式的参数转成键值对,并以&分
/**
* 把对象格式的参数转成键值对,并以&分割
* @param arr 要转换的对象参数
* @returns {string}
*/
function maiyaBuildParam(arr){
var result = '';
for(var key in arr)
{
result += key + "=" + encodeURIComponent(arr[key]) + "&";
}
result = result.substr(0,result.length-1);
return result;
}
9、刷新当前页面
//刷新当前页面
location.reload();
10、强制页面横屏展示
$( window ).on( "orientationchange", function( event ) {
if (event.orientation=='portrait') {
$('body').css('transform', 'rotate(90deg)');
} else {
$('body').css('transform', 'rotate(0deg)');
}
});
$( window ).orientationchange();
11、时间倒计时
function countdown() {
var endtime = new Date("May 2, 2023 00:00:00");
var nowtime = new Date();
if (nowtime >= endtime) {
document.getElementById("clock").innerHTML = "倒计时间结束";
return;
}
var leftsecond = parseInt((endtime.getTime() - nowtime.getTime()) / 1000);
if (leftsecond < 0) {
leftsecond = 0;
}
d = parseInt(leftsecond / 3600 / 24);
h = parseInt((leftsecond / 3600) % 24);
m = parseInt((leftsecond / 60) % 60);
s = parseInt(leftsecond % 60);
document.getElementById("clock").innerHTML = d + "天" + h + "小时" + m + "分" + s + "秒";
}
countdown();
setInterval(countdown, 1000);
12、翻转字符串
const reverse = str => str.split('').reverse().join('');
13、检测用户处于暗模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
14、实现base64解码
function base64_decode(data) {
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1,
o2,
o3,
h1,
h2,
h3,
h4,
bits,
i = 0,
ac = 0,
dec = "",
tmp_arr = [];
if (!data) {
return data;
}
data += "";
do {
h1 = b64.indexOf(data.charAt(i++));
h2 = b64.indexOf(data.charAt(i++));
h3 = b64.indexOf(data.charAt(i++));
h4 = b64.indexOf(data.charAt(i++));
bits = (h1 << 18) | (h2 << 12) | (h3 << 6) | h4;
o1 = (bits >> 16) & 0xff;
o2 = (bits >> 8) & 0xff;
o3 = bits & 0xff;
if (h3 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1);
} else if (h4 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1, o2);
} else {
tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
}
} while (i < data.length);
dec = tmp_arr.join("");
dec = utf8_decode(dec);
return dec;
}
15、获取URL上的参数
// 获取URL中的某参数值,不区分大小写
// 默认是取'hash'里的参数,
// 如果传其他参数支持取‘search’中的参数
// @param {String} name 参数名称
export function getUrlParam(name, type = "hash") {
let newName = name,
reg = new RegExp("(^|&)" + newName + "=([^&]*)(&|$)", "i"),
paramHash = window.location.hash.split("?")[1] || "",
paramSearch = window.location.search.split("?")[1] || "",
param;
type === "hash" ? (param = paramHash) : (param = paramSearch);
let result = param.match(reg);
if (result != null) {
return result[2].split("/")[0];
}
return null;
}
16、修改url中的参数
/**
* @param { string } paramName
* @param { string } replaceWith
*/
export function replaceParamVal(paramName,replaceWith) {
var oUrl = location.href.toString();
var re=eval('/('+ paramName+'=)([^&]*)/gi');
location.href = oUrl.replace(re,paramName+'='+replaceWith);
return location.href;
}
17、安卓移动设备访问
function isAndroidMobileDevice() {
return /android/i.test(navigator.userAgent.toLowerCase());
}
18、苹果移动设备访问
function isAppleMobileDevice() {
return /iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent.toLowerCase());
}
19、平滑滚动到页面顶部
export const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
发现更好的工具函数 ,持续更新中...
参考文献
https://github.com/any86/any-...
https://juejin.im/post/5cc7af...
https://juejin.im/post/5da1a0...
https://juejin.im/post/5deb2c...
https://juejin.im/post/5de5be...