songcomutil
Version:
sxj工具库
107 lines (101 loc) • 2.98 kB
JavaScript
//获取文件后缀名
function getFileExt(fileName) {
if (!fileName) return null;
let ext = null;
let name = fileName.toLowerCase();
let i = name.lastIndexOf(".");
if (i > -1) {
ext = name.substring(i);
}
return ext;
}
//判断是不是手机号码
function isMobile(number) {
return /^1[3-9]\d{9}$/.test(number);
}
//防抖
function debounce(func, delay) {
let timer = null;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
}, delay);
}
}
//节流
function throttle(func, delay) {
let timer = null;
return function (...args) {
if (!timer) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
}, delay);
}
}
}
//计算数组平均值
function average(arr) {
const sum = arr.reduce((acc, cur) => acc + cur, 0);
return sum / arr.length;
}
/**
* 根据给定的url,下载服务器上的静态资源文件
* @param {string} url - 静态资源文件的url
* @param {string} filename - 下载文件的名称
*/
function downloadFileFromUrl(url, filename) {
fetch(url)
.then((res) => res.blob())
.then((blob) => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
// 解决在 Safari 中无法下载文件的问题
if (navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
a.target = '_blank';
}
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
// 释放URL对象
window.URL.revokeObjectURL(url);
})
.catch((err) => {
console.error('Error occurred while downloading file:', err);
});
}
/**
* 根据一个key,查找数组中对象key等于某个值的那个对象,并返回
* @param {string} propName - 属性名
* @param {string} propValue - 属性值
*/
function findObjectByProp(array, propName, propValue) {
for (let i = 0; i < array.length; i++) {
const item = array[i];
if (item[propName] === propValue) {
return item;
} else if (Array.isArray(item.children)) {
const found = findObjectByProp(item.children, propName, propValue);
if (found) {
return found;
}
}
}
return null;
}
//更具数组中对象属性排序
function sortByKey(arr, key, order) {
return arr.sort((a, b) => {
if (order === 'asc') {
return a[key] - b[key];
} else if (order === 'desc') {
return b[key] - a[key];
}
});
}
module.exports={
getFileExt,findObjectByProp,sortByKey,throttle,average,downloadFileFromUrl,isMobile,debounce
}