1.深拷贝对象:
const deepCopy = obj => JSON.parse(JSON.stringify(obj));
structuredClone(obj)
2.等待函数:
const wait = (ms) => new Promise(resolve=>setTimeout(resolve,ms));
const asyncFn = async () =>{
await wait(1000);
console.log('等待异步函数执行结束')
}
asyncFn();
3.隐藏元素
// 我们可以将元素的 style.visibility 设置为 hidden,隐藏元素的可见性,但元素的空间仍然会被占用。如果设置元素的 style.display 为 none,会将元素从渲染流中删除。
const hideElement = (el,removeFromFlow = false) =>{
removeFromFlow?(el.style.display = 'none'):(el.style.visibility = 'hidden')
}
4.从 URL 中获取参数
// JavaScript 中有一个 URL 对象,通过它可以非常方便的获取 URL 中的参数
const getParamByUrl = (key) =>{
const url = new URL(location.href);
return url.searchParams.get(key);
}
5.检测元素是否在屏幕中
// 检查元素是否在窗口中最好的方法是使用 IntersectionObserver
const callback = (entries) =>{
entries.forEach((entry)=>{
if(entry.isIntersecting){
// `entry.target` is the dom element
console.log(`${entry.target.id} is visible`)
}
})
}
const options = {
threshold:1.0,
}
const observer = new IntersectionObserver(callback,options)
const btn = document.getElementById("btn")
const bottomBtn = document.getElementById("bottom-btn")
observer.observe(btn)
observer.observe(bottomBtn)
6.检测设备
const detectDeviceType = () =>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test()?"Mobile":"Desktop";
console.log(detectDeviceType());
7.滚动到顶部
const scrollToTop = (element) => element.scrollIntoView({behavior:"smooth",block:"start"});
8.滚动到底部
const scrollToBottom = (element) => element.scrollIntoView({behavior:"smooth",block:"end"});
9.复制到剪切板
const copyToClipboard = (text) =>navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text);
copyToClipboard("Hello World!")
10. 检测暗色主体
const isDarkMode = () =>window.matchMedia && window.matchMedia("(prefers-color-scheme:dark)").matches;
console.log(isDarkMode());
11.生成随机颜色
const generateRandomHexColor = () =>`#${Math.floor(Math.random()*0xffffff).toString(16)}`;
console.log(generateRandomHexColor());
12.数组重排序
// 对数组的元素进行重新排序是一项非常重要的技巧,但是原生 Array 中并没有这项功能。
const shuffle = (arr) => arr.sort(()=>Math.random()-0.5)
const arr = [1,2,3,4,5]
console.log(shuffle(arr))