成为更好的开发人员必须了解的重要 Javascript 函数
大家好,今天我将展示一些重要的 Javascript 函数的示例。
深层复制
JavaScript 允许您通过将对象转换为字符串然后再转换回对象来进行深度复制。
以下是一个例子:
const deepCopy = (obj) => {
JSON.parse(JSON.stringify(obj))
};
等待函数
JavaScript 可以使用 setTimeout 函数来实现,
但它不返回 Promise 对象,因此在异步函数中很难使用。因此,我们必须编写自己的 wait sleep 函数。
以下是示例:
const wait = new Promise((resolve) => setTimeout(resolve, ms));
const asyncFunction = async() => {
await wait(1000);
console.log("async");
};
asyncFunction();
路口观察员
你可以检查某个元素在视口中是否可见。
我将使用intersectionObserver()
来检查某个元素在视口中是否可见。
const callback = (entries) => {
entries.foreach((entry) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
//enter target in dom element.
//e.g entry.target.classList.add('animated');
console.log(`${entry.target} is visible`);
}
});
};
const options = {
threshold: 1.0,
};
const observer = new IntersectionObserver(callback, options);
const btn = document.getElementById('.btn');
const bottomBtn = document.getElementById('.bottomBtn');
observer.observe(btn);
observer.observe(bottomBtn);
使用选项参数自定义观察者的行为。threshold是最有用的属性。它定义了元素 需要在浏览器触发器的视口中可见的
百分比。
隐藏元素
你可以使用 style.visiabilty 属性切换元素的可见性,如果想将其从渲染流中移除,可以使用style.display属性。
以下是示例:
const hideElement = (element, removeFromFlow = false) => {
removeFromFlow
?
(element.style.display = 'none') :
(element.style.visibility = 'hidden');
}
获取 URL 参数
轻松从 URL 对象中搜索参数。
以下是示例:
const url = new URL(window.location.href);
const paramterValue = url.searchParams.get("pramaName");
console.log(paramterValue);
检测设备类型
使用navigator.UserAgent检测正在运行应用的设备。
示例如下:
const dectectDeviceType = () =>
/Andriod|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent
) ?
"mobile" :
"desktop";
console.log(dectectDeviceType);
如果您不从渲染流中移除元素,它将被隐藏,但其空间将被占用。这在渲染长元素列表时非常有用。可以使用IntersectionObserver
测试不在视图中的元素,并隐藏它们以提升性能。