常用方法

常用的工具函数

new Map

new Map MDN: https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Map

Copy
const map = new Map();
map.set("first",1); // 输出结构 Map(2) {'first' => 1}
map.has("first") // true 回去has表中查找有没有一个键值是匹配有则 true 无则false
map.get("first") // 1 获取到该键所对应的值 没有返回undefined

/**
* for of 方法迭代Map
*/
const map = new Map();
map.set(1,"one");
map.set(2,"two");
for (let [key,value] of map){ // 可以同时拿到key value
console.log(key,value) // 1,one 2,two
}
for (let key of map.keys()){ // 只能拿到键值
console.log(key) // 1 2
}

/**
* 俩数之和的算法题
* @param {number[]} nums
* @param {number} target
* @return {number[]}
*/
const twoSum = function(nums, target) {
const map = new Map();
for(let i = 0;i<nums.length;i++){
if(map.has(target - nums[i])){
return [map.get(target - nums[i]),i]
}else{
map.set(nums[i],i)
}
}
};

const nums = [2,4,5,7,10]

const target = 14

twoSum(nums,target) // [1,4] 输出等于target值 各自数值的下标

字符串数字反转

Copy
/**
* @param {number} num
* @return {boolean}
*/
const isPalindrome = function(num) {
if (num === 0){
return true;
}
const str = num + '';
let result = '';
for (let i = 0;i<str.length;i++){
result += str[str.length-1-i];
}
if (str === result){
return true;
}else{
return false;
}
}

字符串转换 -（驼峰转下划线 / 下划线转驼峰）

Copy
/**
* 下划线转驼峰
* @return
*/
const toHump = (result) => {
return result.replace(/\_(\w)/g, function(_, res){
return res.toUpperCase();
});
}

/**
* 驼峰转换下划线
* @return
*/
const toUnderline = (result) => {
return result.replace(/([A-Z])/g,"_$1").toLowerCase();
}

localStorage 操作

Copy
class Catch {
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 (err) {
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.lenght;
}
}

const localCache = new Catch();
const sessionCache = new Catch(false);

export { localCache, sessionCache };

cookie 操作

Copy
/**
* 获取cookie
* @return string
*/
const getCookie = (name) => {
const strcookie = document.cookie;//获取cookie字符串
const arrcookie = strcookie.split("; ");//分割
for ( let i = 0; i < arrcookie.length; i++) {
const arr = arrcookie[i].split("=");
if (arr[0] == name){
return arr[1];
}
}
return "";
}

/**
* 获取所有cookie
* @return string
*/
const print = () => {
const strcookie = document.cookie;//获取cookie字符串
const arrcookie = strcookie.split(";");//分割
for ( let i = 0; i < arrcookie.length; i++) {
const arr = arrcookie[i].split("=");
console.log(arr[0] +"=" + arr[1]);
}
}
const print = () => {
return eval('({' + document.cookie.replaceAll('=', ":'").replaceAll(';', "',") + "'})");
}

/**
* cookie 增删改
*/
const cookieManager = {
set(key, val) {
//设置cookie方法
const date = new Date(); //获取当前时间
const expiresDays = 1; // 1天
date.setTime(date.getTime() + expiresDays * 24 * 3600 * 1000); //格式化为cookie识别的时间
document.cookie = key + '=' + val + ';expires=' + date.toGMTString(); //设置cookie
console.log(key + '=' + val + ';expires=' + date.toGMTString(),'val....')
},
get(key) {
//获取cookie方法
/*获取cookie参数*/
const cookies = document.cookie.replace(/[ ]/g, ''); //获取cookie，并且将获得的cookie格式化，去掉空格字符
const arrCookie = cookies.split(';'); //将获得的cookie以"分号"为标识 将cookie保存到arrCookie的数组中
let tips; //声明变量tips
for (let i = 0; i < arrCookie.length; i++) {
//使用for循环查找cookie中的tips变量
const arr = arrCookie[i].split('='); //将单条cookie用"等号"为标识，将单条cookie保存为arr数组
if (key == arr[0]) {
//匹配变量名称，其中arr[0]是指的cookie名称，如果该条变量为tips则执行判断语句中的赋值操作
tips = arr[1]; //将cookie的值赋给变量tips
break; //终止for循环遍历
}
}
return tips;
},
del(key) {
//删除cookie方法
const date = new Date(); //获取当前时间
date.setTime(date.getTime() - 10000); //将date设置为过去的时间
document.cookie = key + '=v; expires =' + date.toGMTString(); //设置cookie
},
};

节流防抖（测试用例）

Copy
/**
* 防抖
*/
const debounce = (fn, delay) => {
let timer;
return function () {
const arg = arguments;
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(() => {
fn.apply(this, arg);
}, delay);
};
};

/**
* 节流
*/
const throttle = (fn, delay) => {
let timer;
return function () {
let _this = this;
let args = arguments;
if (timer) {
return;
}
timer = setTimeout(function () {
fn.apply(_this, args);
timer = null;
}, delay);
};
};

/**
* 时间戳节流
*/
function timestamThrottle(fn, delay) {
let previous = 0;
// 使用闭包返回一个函数并且用到闭包函数外面的变量previous
return function () {
let now = new Date();
if (now - previous > delay) {
fn.apply(this, arguments);
previous = now;
}
};
}

/**
* 测试用例
* 以防抖函数为例子
*/
const debounceFn = debounce((e) => {
console.log(e);
}, 500); // 防抖函数
document.onmousemove = (e) => {
debounceFn(e); // 给防抖函数传参
};

监听复制 / 剪切

Copy
/**
* 监听复制
*/
(function () {
document.addEventListener('copy', (e) => {
const selection = document.getSelection();
e.clipboardData.setData('text/plain', selection.toString().toUpperCase());
e.preventDefault();
e.stopPropagation();
let copy = (e.clipboardData || window.clipboardData).getData('text/plain');
copy = copy.replace(/style/gi, 'data-style');
console.log(copy, 'copy');
});
})();

/**
* 监听剪切
*/
(function () {
document.addEventListener('cut', (e) => {
const selection = document.getSelection();
e.clipboardData.setData('text/plain', selection.toString().toUpperCase());
document.getSelection().deleteFromDocument();
e.preventDefault();
e.stopPropagation();
let cut = (e.clipboardData || window.clipboardData).getData('text/plain');
cut = cut.replace(/style/gi, 'data-style');
console.log(cut, 'cut');
});
})();

递归

Copy
/**
* 返回当前数据所有父结构数据(包括自己)
* @param list = []
* @param id: number
*/
function getParentId(list, id) {
for (let i in list) {
if (list[i].value == id) {
return [list[i]];
}
if (list[i].children) {
let node = getParentId(list[i].children, id);
if (node !== undefined) {
return node.concat(list[i]);
}
}
}
}

/**
* 递归查找指定数据
* @param list = []
* @param id: number
*/
function getCurrent(list, id) {
for (let o of list || []) {
if (o.value == id) return o
const o_ = getCurrent(o.children, id)
if (o_) return o_
}
}

// parentId 和 id 相同时变成id的子集数据
//初始数据
var data = [
{ id: 2, parentId: 1 },
{ id: 1 },
{ id: 3, parentId: 2 },
{ id: 5, parentId: 4 },
{ id: 4 },
];
//处理后的数据
/*[
{
id: 1,
child: [{
id: 2,
parentId: 1,
child: [{
id: 3,
parentId: 2
}]
}]
},
{id: 4, child: [{id: 5, parentId: 4}]},
]*/
function returnData(arr) {
//初始没有上级的数据和
let parents = arr.filter((item) => !item.parentId);
//初始有上级的数据和
let childs = arr.filter((item) => item.parentId);
//递归处理数据
function newData(parents, childs) {
parents.forEach((item) => {
childs.forEach((child, childIndex) => {
if (item.id === child.parentId) {
let newChilds = JSON.parse(JSON.stringify(childs));
newChilds.splice(childIndex, 1); //删除已经存在的数据
item.childs = item.childs ? item.childs.push(child) : [child];
newData([child], newChilds);
} else {
return false;
}
});
});
}
newData(parents, childs);
return parents;
}
let a = [];
console.log((a = returnData(data)));

// 筛选/过滤
// 例子
const memberList = [
{
name: "研发部",
member: [
{
name: "前端",
member: [
{
name: "张三",
age: 18,
member: [],
},
],
},
{
name: "后端",
member: [
{
name: "李四",
age: 24,
member: [],
},
],
},
],
},
{
name: "市场部",
member: [
{
name: "主管",
member: [
{
name: "王五",
age: 30,
member: [],
},
],
},
{
name: "经理",
member: [
{
name: "老六",
age: 28,
member: [],
},
],
},
],
},
];

// 过滤 name 值 并以数组的形式返回
const getAllMember = (arr) => {
let member = [];
arr.forEach(item => {
if (item.member && item.member.length) {
member = [
...member,
...getAllMember(item.member)
]
} else {
member.push(item.name);
}
});
return member;
}

// 筛选 age 小于 20 的数据
const filterMember = (key, data) => {
const filterList = [];

data.forEach((ele) => {
const { member, ...other } = ele;

if (member && member.length) {
const currentEle = {
member: [],
...other,
};
const result = filterMember(key, member);

if (result.length) {
currentEle.member = result;
filterList.push(currentEle);
}
} else if (other.age > key) {
filterList.push(other);
}
});
return filterList;
};

监听用户是否打开 devtools 行为

Copy
(function () {
var devtools = {
open: false,
orientation: null,
};
var threshold = 160;
var emitEvent = function (state, orientation) {
window.dispatchEvent(
new CustomEvent("devtoolschange", {
detail: {
open: state,
orientation: orientation,
},
})
);
};
clearTimer = setInterval(function () {
var widthThreshold = window.outerWidth - window.innerWidth > threshold;
var heightThreshold = window.outerHeight - window.innerHeight > threshold;
var orientation = widthThreshold ? "vertical" : "horizontal";

if (
!(heightThreshold && widthThreshold) &&
((window.Firebug &&
window.Firebug.chrome &&
window.Firebug.chrome.isInitialized) ||
widthThreshold ||
heightThreshold)
) {
if (!devtools.open || devtools.orientation !== orientation) {
emitEvent(true, orientation);
}
devtools.open = true;
devtools.orientation = orientation;
} else {
if (devtools.open) {
emitEvent(false, null);
}
devtools.open = false;
devtools.orientation = null;
}
}, 500);
if (typeof module !== "undefined" && module.exports) {
module.exports = devtools;
} else {
window.devtools = devtools;
}
})();

windown.addEventListener("devtoolschange", function (e) {
console.log(e.detail)
});

监听某个元素的实时变化

Copy
/**
* 监听某个元素的实时变化
*/
export const ListeningTagAttribute = () => {
setTimeout(() => {
//选择要监听的元素
const targetNode = document.getElementById('detail-content');

// 创建一个观察器实例并传入回调函数
const observer = new MutationObserver((mutationsList, observer) => {
// 循环遍历每个变化
for (let mutation of mutationsList) {
console.log(mutation, mutationsList)
if (mutation.type === 'attributes') {
console.log('属性值已改变:', mutation.attributeName, mutation.target.getAttribute(mutation.attributeName));
}
}
});

// 配置观察器选项
const config = { attributes: true, childList: false, subtree: false };
//传入目标节点和观察器的配置对象
observer.observe(targetNode, config);
}, 3000)
}

对 URL 的解析 / 和对 URL 参数的字段替换处理

Copy
/**
* @param {string} url 地址
* @param {string} arg 需要替换的参数名称
* @param {any} arg_val 需要替换的参数
* @returns 返回处理后的url
*/
function changeURLArg(url,arg,arg_val){
let pattern=arg+'=([^&]*)';
let replaceText=arg+'='+arg_val;
if(url.match(pattern)){
let tmp='/('+ arg+'=)([^&]*)/gi';
tmp=url.replace(eval(tmp),replaceText);
return tmp;
}else{
if(url.match('[\?]')){
return url+'&'+replaceText;
}else{
return url+'?'+replaceText;
}
}
return url+'\n'+arg+'\n'+arg_val;
}

// 解析成对象
function queryURLparams(url) {
let obj = {}
if (url.indexOf('?') < 0) return obj
let arr = url.split('?')
url = arr[1]
let array = url.split('&')
for (let i = 0; i < array.length; i++) {
let arr2 = array[i]
let arr3 = arr2.split('=')
obj[arr3[0]] = arr3[1]
}
return obj
}

function queryURLparamsRegEs5(url) {
let obj = {}
let reg = /([^?=&]+)=([^?=&]+)/g
url.replace(reg, function() {
obj[arguments[1]] = arguments[2]
})
return obj
}

function queryURLparamsRegEs6(url) {
let obj = {}
let reg = /([^?=&]+)=([^?=&]+)/g
url.replace(reg, (...arg) => {
obj[arg[1]] = arg[2]
})
return obj
}

/**
* @param {string} param 需要添加在url地址后面的参数
* @returns
*/
function addParameterToURL(param) {
let _url = location.href;
_url += (_url.split('?')[1] ? '&' : '?') + param;
return _url;
}

UUID

Copy
function UUID() {
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4";
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
s[8] = s[13] = s[18] = s[23] = "-";

var UUID = s.join("");
return UUID;
}

function UUID() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});

}

function UUID() {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

function uuid2(len, radix) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
var uuid = [],i;
radix = radix || chars.length;

if (len) {
for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
} else {
var r;

uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
uuid[14] = '4';

for (i = 0; i < 36; i++) {
if (!uuid[i]) {
r = 0 | Math.random() * 16;
uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
}
}
}

return uuid.join('');
}

模糊搜索

Copy
const listdata = [
{
id: 1,
name: "哈喽",
},
{
id: 2,
name: "哈haha",
},
{
id: 3,
name: "xiaoyang喽",
},
];

function fuzzyQuery(list, keyWord, arrtibute = "name") {
const reg = new RegExp(keyWord);
const arr = [];
for (let i = 0; i < list.length; i++) {
if (reg.test(list[i][arrtibute])) {
arr.push(list[i]);
}
}
return arr;
};

console.log(fuzzyQuery(listdata, "喽", "name")); // [{id: 1, name: '哈喽'}1: {id: 3, name: 'xiaoyang喽'}]

数组扁平化

Copy
const arr = [
{
id: 1,
name: 'node-1',
},
{
id: 2,
name: 'node-2',
children: [
{
id: 3,
name: 'node-3',
},
{
id: 4,
name: 'node-4',
children: [
{
id: 5,
name: 'node-5',
},
],
},
],
},
];

/**
* 扁平化
*/
const result = arr.reduce(function (prev, current) {
prev.push({
id: current.id,
name: current.name,
parent: current.parentId,
});
current.children &&
current.children.forEach((v) => {
v.parentId = current.id;
arguments.callee(prev, v);
});
return prev;
}, []);

const map = [
{
id: 1,
name: 'ndoe-1',
parentId: undefined,
},
{
id: 2,
name: 'ndoe-2',
parentId: undefined,
},
{
id: 3,
name: 'ndoe-3',
parentId: 2,
},
{
id: 4,
name: 'ndoe-4',
parentId: 2,
},
{
id: 5,
name: 'ndoe-5',
parentId: 4,
},
];

/**
* 扁平化转树结构
*/
const result = map.reduce(function (prev, current, i, arr) {
current.children = a = arr.filter((v) => v.parentId === current.id);
if (!current.parentId) {
prev.push(current);
}
return prev;
}, []);

function flatten(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
};

function flatMap(list = [], id: number) {
return list.flatMap(({children, ...other}) => {
return [other].concat(flatMap(children))
})
}

去重

Copy
// 数组对象去重
const duplicateRemoval = edgesdata.filter((item) => !line.some((ele) => ele?.id === item?.id));

// 数组去重 [1,2,1,2,1,3,3,3]
function duplicateRemoval(arr) {
const res = new Map();
return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
}

// 数组去重 [1,2,1,2,1,3,3,3]
const duplicateRemoval = (arr) => [...new Set(arr)];

// 数组去重合并相同数据
function handlerArrayMerge(value){
const tempIds = [],newArrs = [];
for(const item of value){
if(!tempIds.includes(item.id)){
tempIds.push(item.id);
newArrs.push(item);
}else{
for(const ele of newArrs){
if(ele.id === item.id){
ele.children = handlerArrayMerge(ele.children.concat(item.children));
}
}
}
}
return newArrs;
}

正则校验

Copy
// 判断字符串是 html 格式
function isHtml(str) {
return /<[a-z]+\d?(\s+[\w-]+=("[^"]*"|'[^']*'))*\s*\/?>|&#?\w+;/i.test(str);
}

对数字的处理

Copy
const num = 12.34567;

// 保留2位小数，不四舍五入
Math.floor(num * 100) / 100 // 输出结果为 12.34

// 保留2位小数，四舍五入
num.toFixed(2); // 输出结果为 12.35

//四舍五入保留2位小数（不够位数，则用0替补）
function keepTwoDecimals(num) {
let result = parseFloat(num);
if (isNaN(result)) {
// 参数不符合要求
return false;
}
result = Math.round(num * 100) / 100;
let rt = result.toString();
let pos = rt.indexOf('.');
if (pos < 0) {
pos = rt.length;
rt += '.';
}
while (rt.length <= pos + 2) {
rt += '0';
}
return rt;
}

keepTwoDecimals(124); // 输出结果 124.00

定时器处理

Copy
/**
* 定时器计时、暂停、继续
*/
class timerRecording {
timerId = undefined;
// 定义一个变量，用于记录暂停时的时间
pauseTime = 0;
// 定义一个变量，用于记录计时器开始时间
startTime = 0;

startTimer() {
// 如果已经有计时器在运行，则直接返回
if (this.timerId) {
return;
}

// 记录计时器开始时间
this.startTime = Date.now();

// 启动计时器，每隔1秒执行一次回调函数
this.timerId = setInterval(() => {
// 计算已经经过的时间
let elapsed = Date.now() - this.startTime + this.pauseTime;

// 将已经经过的时间格式化为 HH:MM:SS 的形式
// let hours = Math.floor(elapsed / (60 * 60 * 1000));
// let minutes = Math.floor((elapsed - hours * 60 * 60 * 1000) / (60 * 1000));
// let seconds = Math.floor((elapsed - hours * 60 * 60 * 1000 - minutes * 60 * 1000) / 1000);
// let timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

// 转换成累加的秒
let seconds = parseInt(elapsed / 1000);

// 将格式化后的时间显示在当前文章的标签属性上
document
.getElementById('detail-content')
?.setAttribute('data-time', seconds);
}, 1000);
}

// 暂停计时器
pauseTimer() {
// 如果没有计时器在运行，则直接返回
if (!this.timerId) {
return;
}

// 清除计时器
clearInterval(this.timerId);

// 记录暂停时的时间
this.pauseTime += Date.now() - this.startTime;

// 清空计时器 ID
this.timerId = null;
}
// 继续计时器
continueTimer() {
// 如果已经有计时器在运行，则直接返回
if (this.timerId) {
return;
}

// 记录计时器开始时间
this.startTime = Date.now();

// 启动计时器，每隔1秒执行一次回调函数
this.timerId = setInterval(() => {
// 计算已经经过的时间
let elapsed = Date.now() - this.startTime + this.pauseTime;

// 将已经经过的时间格式化为 HH:MM:SS 的形式
// let hours = Math.floor(elapsed / (60 * 60 * 1000));
// let minutes = Math.floor((elapsed - hours * 60 * 60 * 1000) / (60 * 1000));
// let seconds = Math.floor((elapsed - hours * 60 * 60 * 1000 - minutes * 60 * 1000) / 1000);
// let timeString = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;

// 转换成累加的秒
let seconds = parseInt(elapsed / 1000);

// 将格式化后的时间显示在当前文章的标签属性上
document
.getElementById('detail-content')
?.setAttribute('data-time', seconds);
}, 1000);
}
}

const timerRecord = new timerRecording();
export { timerRecord };