1. 深拷贝函数

用于复制对象或数组,新对象和原对象互不影响。

<pre class="code-snippet__js" data-lang="bash">function deepClone(obj) {    if (typeof obj !== 'object' || obj === null) {        return obj;    }    let clone;    if (Array.isArray(obj)) {        clone = [];        for (let i = 0; i < obj.length; i++) {            clone[i] = deepClone(obj[i]);        }    } else {        clone = {};        for (let key in obj) {            if (obj.hasOwnProperty(key)) {                clone[key] = deepClone(obj[key]);            }        }    }    return clone;}

2. 防抖函数

在一定时间内format函数,若事件被多次触发,仅执行最后一次。常用于搜索框输入提示等场景。

function debounce(func, delay) {    let timer = null;    return function() {        const context = this;        const args = arguments;        clearTimeout(timer);        timer = setTimeout(() => {            func.apply(context, args);        }, delay);    };}

3. 节流函数

在一定时间内,事件只能触发一次。常用于滚动加载、按钮点击等场景。

function throttle(func, limit) {    let inThrottle;    return function() {        const context = this;        const args = arguments;        if (!inThrottle) {            func.apply(context, args);            inThrottle = true;            setTimeout(() => inThrottle = false, limit);        }    };}

4. 生成随机字符串函数

能生成指定长度的随机字符串format函数,可用于生成唯一 ID 等。

function generateRandomString(length) {    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';    let result = '';    for (let i = 0; i < length; i++) {        result += characters.charAt(Math.floor(Math.random() * characters.length));    }    return result;}

5. 检查对象是否为空函数

判断一个对象是否不包含任何属性。

function isEmptyObject(obj) {    return Object.keys(obj).length === 0;}

6. 获取 URL 参数函数

从 URL 中获取指定参数的值。

function getUrlParam(name) {    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');    const r = window.location.search.substr(1).match(reg);    if (r != nullreturn decodeURIComponent(r[2]);    return null;}

7. 日期格式化函数

把日期对象格式化为指定格式的字符串。

function formatDate(date, format) {    const o = {        'M+': date.getMonth() + 1,        'd+': date.getDate(),        'h+': date.getHours(),        'm+': date.getMinutes(),        's+': date.getSeconds(),        'q+'Math.floor((date.getMonth() + 3) / 3),        'S': date.getMilliseconds()    };    if (/(y+)/.test(format)) {        format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));    }    for (let k in o) {        if (new RegExp('(' + k + ')').test(format)) {            format = format.replace(RegExp.$1, (RegExp.$1.length === 1)? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));        }    }    return format;}


限时特惠:
本站持续每日更新海量各大内部创业课程,一年会员仅需要98元,全站资源免费下载
点击查看详情

站长微信:Jiucxh

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注