返回
踏上前端征程:必备的JS函数集锦(下)
前端
2023-11-04 13:08:05
前言
从初学者到经验丰富的前端开发人员,JavaScript函数都是开发工作中不可或缺的一部分。在本文中,我们将继续深入探究更多实用的JS函数,为您的前端开发之旅再添利器。
函数锦囊
1. 函数节流(throttling)
函数节流是指在指定的时间间隔内,只允许函数执行一次。这对于防止函数被重复调用非常有用,尤其是在事件频繁发生的情况下。
function throttle(fn, delay) {
let timer = null;
return function () {
let context = this,
args = arguments;
if (!timer) {
timer = setTimeout(() => {
fn.apply(context, args);
timer = null;
}, delay);
}
};
}
// 使用示例
const handleClick = () => {
console.log("Button clicked!");
};
const throttledClickHandler = throttle(handleClick, 500);
// 为按钮绑定节流后的点击事件处理函数
document.querySelector("button").addEventListener("click", throttledClickHandler);
2. 函数防抖(debounce)
函数防抖是指在指定的时间间隔内,只有当函数停止被调用后,才会执行一次。这对于防止函数在短时间内被重复调用非常有用。
function debounce(fn, delay) {
let timer = null;
return function () {
let context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(() => {
fn.apply(context, args);
}, delay);
};
}
// 使用示例
const handleSearch = () => {
// 模拟搜索操作
console.log("Searching...");
};
const debouncedSearchHandler = debounce(handleSearch, 500);
// 为输入框绑定防抖后的搜索事件处理函数
document.querySelector("input").addEventListener("input", debouncedSearchHandler);
3. 深拷贝(deep copy)
深拷贝是指将一个对象的所有属性及其嵌套对象都复制一份,生成一个新的对象。这与浅拷贝不同,浅拷贝只复制对象的第一层属性,而深拷贝会递归复制所有层级的属性。
function deepCopy(obj) {
if (typeof obj !== "object" || obj === null) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map(item => deepCopy(item));
}
const newObj = {};
for (const key in obj) {
newObj[key] = deepCopy(obj[key]);
}
return newObj;
}
// 使用示例
const originalObj = {
name: "John Doe",
age: 30,
address: {
street: "123 Main Street",
city: "Anytown",
state: "CA",
},
};
const copiedObj = deepCopy(originalObj);
// 修改复制后的对象
copiedObj.name = "Jane Smith";
copiedObj.address.city = "New York";
// 打印两个对象
console.log(originalObj);
console.log(copiedObj);
4. 数组去重(array distinct)
数组去重是指从数组中移除重复的元素,只保留唯一元素。这对于处理包含重复元素的数组非常有用。
function arrayDistinct(arr) {
return Array.from(new Set(arr));
}
// 使用示例
const arr = [1, 2, 3, 4, 5, 1, 2, 3];
const distinctArr = arrayDistinct(arr);
console.log(distinctArr); // [1, 2, 3, 4, 5]
5. 洗牌算法(shuffle)
洗牌算法是指将数组中的元素随机打乱顺序。这对于生成随机列表或序列非常有用。
function shuffle(arr) {
let currentIndex = arr.length,
randomIndex;
// 从后往前遍历数组
while (currentIndex != 0) {
// 随机选取一个索引
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// 交换当前元素和随机选取的元素
[arr[currentIndex], arr[randomIndex]] = [
arr[randomIndex],
arr[currentIndex],
];
}
return arr;
}
// 使用示例
const arr = [1, 2, 3, 4, 5];
const shuffledArr = shuffle(arr);
console.log(shuffledArr); // [5, 3, 2, 4, 1]
结语
这些只是工作中常用的JS函数库中的几个例子。还有许多其他有用的函数,您可以根据自己的需要进行探索和学习。掌握这些函数将帮助您提高前端开发效率,并为您的项目带来更多的可能性。
不断学习和实践,您将成为一名更加熟练和自信的前端开发人员。希望这些函数能为您的开发之旅锦上添花,助您轻松应对各种开发挑战。