1、数组去重(es6)
let arr = [1,1,2,3,2,4,3];
Array.from(new Set(arr));
console.log(arr); //[1,2,3,4]
2、query参数解析
function getUrlParameters(url) {
if (!url) {
return;
}
const paramsStr = url.split('?')[1];
const array = paramsStr.split('&');
let result = {};
array.forEach((element) => {
const temp = element.split('=');
result[temp[0]] = temp[1];
});
return result;
}
3、实现复制功能
function copy(url){
event.stopPropagation();
let copyInput = document.createElement('input');//创建input元素
document.body.appendChild(copyInput);//向页面底部追加输入框
copyInput.setAttribute('value', url);
copyInput.select();//选择元素
document.execCommand("Copy");//执行复制命令
//弹窗提醒,使用layui组件
layer.msg('复制成功');
//复制完成移除input
copyInput.remove()
}
4、时间类组件,可使用day.js
https://dayjs.fenxianglu.cn/
5、数据扁平化
function treeFlat(data) {
let result = [];
data.forEach((item) => {
result.push(item);
if (item?.children?.length > 0) {
result = result.concat(treeFlat(item.children));
}
});
return result;
}
6、a标签下载文件
fetch(resourcePath).then(function (res) {
res.blob().then(function (blob) {
let a = document.createElement('a');
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = '';//空字符串取默认名称
a.click();
window.URL.revokeObjectURL(url);
a = null;
});
});
7、IntersectionObserver。在Web应用中,可能需要实现无限滚动、懒加载等功能,使用IntersectionObserver可以方便地实现这些功能。
const myObserver = new IntersectionObserver((entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
console.log(`${entry.target.id} is now visible`);
observer.unobserve(entry.target);
}
});
});
const myElement = document.getElementById("myElement");
myObserver.observe(myElement);
8、将数据拼成树状结构
function buildTree(data, parentId = null) {
const tree = [];
for (const item of data) {
if (item.pid === parentId) {
const children = buildTree(data, item.id);
if (children.length > 0) {
item.children = children;
}
tree.push(item);
}
}
return tree;
}
const dataArray = [
{
"name": "部门12",
"pid": "c94eaf83acb00001206b1c1760054300",
"id": "c94eb2f2112000018747e2d010001d1c"
},
// ... 其他对象
];
const treeArray = buildTree(dataArray);
console.log(JSON.stringify(treeArray, null, 2));