树形数据结构中找到其中一条数据
1、利用递归
const findPropsIdData = (dataList, id, propsId) => {
const findFromData = (data) => {
for (let i = 0, len = data.length
if (String(data[i][propsId]) === String(id)) return data[i]
const { children } = data[i]
if (children && children.length) {
const findDataFromChildren = findFromData(children)
if (findDataFromChildren) return findDataFromChildren
}
}
}
return findFromData(dataList)
}
匹配字符串的括号是否合法
1、利用正则表达式的做法
const vaild = (str) => {
const filter_list = [/\(([^\(\)\[\]{}])*\)/g, /\[([^\(\)\[\]{}])*\]/g, /{([^\(\)\[\]{}])*}/g]
let length
do {
length = str.length
str = filter_list.reduce((pre, cur) => pre.replace(cur, ''), str)
} while (length !== str.length)
return str.length === 0
}
2、利用栈的入栈出栈原理
const match = (str) => {
let open_handle = ['(', '{', '[']
let handle_pair = {
')': '(',
'}': '{',
']': '['
}
let list = [];
for (let i = 0; i < str.length; i++) {
let s = str[i]
if (open_handle.indexOf(s) > -1) {
list.push(s)
} else if (Object.keys(handle_pair).indexOf(s) > -1) {
if (list.pop() != handle_pair[s]) return false;
}
}
return list.length === 0;
}
判断数据类型
1、Object.prototype.toString
function DataType(tgt, type) {
const dataType = Object.prototype.toString.call(tgt).replace(/\[object (\w+)\]/, "$1").toLowerCase();
return type ? dataType === type : dataType;
}
防抖
const debounce = (fn, delay=300, timer) => (...args) => {
if (timer) clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay)
}
节流
1、节流不太精确的写法
const throtte = (fn, delay=300, canRun=true) => (...args) => {
if(canRun) {
canRun = false
setTimeout(() => {
canRun = true
fn(...args)
}, delay)
}
}
2、节流精确的写法
const throtte = (fn, delay=300, time = performance.now()) => (...args) => {
if (performance.now() - time >= delay) {
time = performance.now();
fn(...args)
}
}
下载文件
const down = (url: string) => {
const aLink = document.createElement('a');
aLink.href = url;
let event;
if (window.MouseEvent) event = new MouseEvent('click');
else {
event = document.createEvent('MouseEvents');
event.initMouseEvent(
'click',
true,
false,
window,
0,
0,
0,
0,
0,
false,
false,
false,
false,
0,
null,
);
}
aLink.dispatchEvent(event);
};