防抖
防抖函数的作用是在一定时间内只执行一次函数,常用于优化用户输入、滚动事件等频繁触发的操作。以下是一个简单的防抖函数实现:
function debounce(func, delay) {
let timerId;
return function() {
const context = this;
const args = arguments;
clearTimeout(timerId);
timerId = setTimeout(() => {
func.apply(context, args);
}, delay);
};
}
节流
节流函数的作用是在一定时间内只执行一次函数,常用于优化频繁触发的操作,如窗口 resize、滚动事件等。以下是一个简单的节流函数实现:
function throttle(func, delay) {
let timerId;
let lastExecutedTime = 0;
return function() {
const context = this;
const args = arguments;
const currentTime = Date.now();
const timeSinceLastExecution = currentTime - lastExecutedTime;
if (timeSinceLastExecution >= delay) {
lastExecutedTime = currentTime;
func.apply(context, args);
} else {
clearTimeout(timerId);
timerId = setTimeout(() => {
lastExecutedTime = currentTime;
func.apply(context, args);
}, delay - timeSinceLastExecution);
}
};
}
深拷贝
深拷贝是指将一个对象完整地复制一份并返回,新对象与原对象互不影响。以下是一个简单的深拷贝实现:
function deepCopy(obj) {
if (typeof obj !== <object< || obj === null) {
return obj;
}
const newObj = Array.isArray(obj) ? [] : {};
for (let key in obj) {
newObj[key] = deepCopy(obj[key]);
}
return newObj;
}
数组去重
const unique = arr => {
if (Array.hasOwnProperty('from')) {
return Array.from(new Set(arr));
} else {
var n = {},
r = [];
for (var i = 0; i < arr.length; i++) {
if (!n[arr[i]]) {
n[arr[i]] = true;
r.push(arr[i]);
}
}
return r;
}
};
字符串去除空格
type: 1-所有空格 2-前后空格 3-前空格 4-后空格
const trim = (str, type = 1) => {
switch (type) {
case 1:
return str.replace(/\s+/g, '');
case 2:
return str.replace(/(^\s*)|(\s*$)/g, '');
case 3:
return str.replace(/(^\s*)/g, '');
case 4:
return str.replace(/(\s*$)/g, '');
default:
return str;
}
};
获取 URL 参数
function getUrlParam(name, url) {
if (!url) url = location.href;
if (url.indexOf('?') == -1) return '';
try {
var re = new RegExp('' + name + '=([^&?]*)', 'ig');
return url.match(re) ? decodeURIComponent(url.match(re)[0].substr(name.length + 1)) : '';
} catch (_e) {
return '';
}
}