代码 18个实用的 JavaScript 函数

2024-11-17 18:10:35 +0800 CST views 492

代码工具箱:18个实用的 JavaScript 函数

本文将分享一些实用的 JavaScript 代码片段,可以帮助你提升代码效率,简化开发流程。这些代码涵盖了常见的需求,例如 URL 处理、缓存清理、获取 CSS 变量等,非常实用。

函数节流 📡

/** 函数节流计时器版本 */
function throttle(callback: Function, delay: number) {
  let timer: number | null;
  return function () {
    if (timer) return;
    const args = arguments; // 使用闭包保存参数数组
    timer = setTimeout(() => {
      callback.apply(null, args);
      timer = null;
    }, delay);
  };
}

URL 解码 & 编码 💻

/** 编码 URL */
function encodeURL(url: string, isComponent = true): string {
  return isComponent ? encodeURIComponent(url) : encodeURI(url);
}

/** 解码 URL */
function decodeURL(url: string, isComponent = true): string {
  return isComponent ? decodeURIComponent(url) : decodeURI(url);
}

使用 JavaScript 获取全局 CSS 变量 📡

/**
 * @description 使用 JS 获取全局 CSS 变量
 * @param cssVariableName 变量名
 * @returns {string} 变量值
 */
function getCssVariableValue(cssVariableName: string): string {
  return getComputedStyle(document.documentElement).getPropertyValue(cssVariableName);
}

使用 JS 设置全局 CSS 变量 💪

/**
 * @description 使用 JS 设置全局 CSS 变量
 * @param {string} cssVariableName 变量名
 * @param {string} cssVariableValue 变量值
 */
function setCssVariableValue(cssVariableName: string, cssVariableValue: string): void {
  document.documentElement.style.setProperty(cssVariableName, cssVariableValue);
}
/**
 * @description 清除所有 cookie
 */
function clearCookie(): void {
  const keyList = document.cookie.match(/[^ =;]+(?=\=)/g) as string[] | null;
  keyList && keyList.forEach(key => (document.cookie = `${key}=0;path=/;expires=${new Date(0).toUTCString()}`));
}

清除所有项目缓存 💾

/**
 * @description 清除所有项目缓存
 */
function clearCache(): void {
  window.localStorage.clear();
  window.sessionStorage.clear();
  const keyList = document.cookie.match(/[^ =;]+(?=\=)/g) as string[] | null;
  keyList && keyList.forEach(key => (document.cookie = `${key}=0;path=/;expires=${new Date(0).toUTCString()}`));
}

按名称获取 URL 查询参数 👤

/**
 * @description 按名称获取 URL 查询参数
 * @param {string} key 需要获取的查询参数的键
 * @param {string} url 需要解析的链接,默认是 window.location.href
 * @returns {string | null} 获取到的对应于 key 的值
 */
function getQueryByName(key, url = window.location.href) {
  const queryNameRegExp = new RegExp(`[?&]${key}=([^&]*)(?:&|$)`);
  const queryNameMatch = url.match(queryNameRegExp);
  return queryNameMatch ? decodeURIComponent(queryNameMatch[1]) : null;
}

登录页面时间前缀🧵

/**
 * @description 登录页面的时间前缀
 * @returns {string} 时间前缀
 */
function timeFix(): string {
  const time = new Date();
  const hour = time.getHours();
  return hour < 9 ? 'Good morning' : hour <= 11 ? 'Good morning' : hour <= 13 ? 'Good afternoon' : hour < 20 ? 'Good afternoon' : 'Good evening';
}

登录页面的欢迎信息 💻

/**
 * @description 登录页面上的欢迎信息
 * @returns {string} 随机欢迎信息
 */
function welcome(): string {
  const list = ['Long time no see, I miss you so much!', 'Wait until the stars go to sleep before I miss you', 'We are open today'];
  return list[Math.floor(Math.random() * list.length)];
}

递归深拷贝 📋

/**
 * @description 对传入的数据进行深拷贝,并返回
 * @param {any} source 数据源
 * @returns {any} 复制后的数据
 */
function deepClone(source: any): any {
  if (!source || typeof source !== 'object') return source;
  if (source instanceof Date) return new Date(source);
  if (source instanceof RegExp) return new RegExp(source);
  const target = Array.isArray(source) ? ([] as Record<any, any>) : ({} as Record<any, any>);
  for (const key in source) target[key] = typeof source[key] === 'object' ? deepClone(source[key]) : source[key];
  return target;
}

随机生成 UUID 📑

/**
 * @description 随机生成 UUID
 * @returns {string} 生成的 uuid
 */
function getRandomUUID(): string {
  const tempURL = URL.createObjectURL(new Blob());
  const uuidStr = tempURL.toString();
  const separator = uuidStr.includes('/') ? '/' : ':';
  URL.revokeObjectURL(tempURL);
  return uuidStr.substring(uuidStr.lastIndexOf(separator) + 1);
}
function getRandomUUID(): string {
  const fn = (): string => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  return fn() + fn() + '-' + fn() + '-' + fn() + '-' + fn() + '-' + fn() + fn() + fn();
}

随机布尔值 🎲

/**
 * @description 随机布尔值
 * @returns {boolean} true | false
 */
function getRandomBoolean(): boolean {
  return Math.random() > 0.5;
}

反转字符串 🔁

/**
 * @description 反转字符串
 * @param {string} str 字符串
 * @returns {string} 反转后的字符串
 */
function reverseString(str: string): string {
  return str.split('').reverse().join('');
}

随机生成十六进制颜色 🎨

/**
 * @description 随机生成一个十六进制格式的颜色字符串
 * @returns {string} 十六进制格式的颜色字符串
 */
function getRandomHexColor(): string {
  return `#${Math.floor(Math.random() * 0xffffff).toString(16)}`;
}

获取变量的真实类型 🔢

/**
 * @description 获取变量的真实类型
 * @param {any} variable 任意类型的变量
 * @returns {string} 变量类型
 */
function getRawType(variable: any): string {
  return Object.prototype.toString.call(variable).split(' ')[1].replace(']', '').toLowerCase();
}

将文本复制到剪贴板 📎

/**
 * @description 将文本复制到剪贴板
 * @param {string} text 要复制的文本
 */
function copyText(text: string): void {
  // 是否支持 navigator.clipboard 属性
  const isClipboardApiSupported = window.navigator && window.navigator.clipboard;
  if (isClipboardApiSupported) {
    window.navigator.clipboard.writeText(text);
  } else {
    const textarea = document.createElement('textarea');
    textarea.readOnly = true;
    textarea.value = text;
    textarea.style.position = 'absolute';
    textarea.style.top = '-9999px';
    textarea.style.left = '-9999px';
    document.body.appendChild(textarea);
    textarea.select();
    document.execCommand('copy');
    textarea.remove();
  }
}

滚动到顶部 ⬆️

/**
 * @description 滚动到顶部
 */
function scrollToTop(element: HTMLElement): void {
  element.scrollIntoView({ behavior: 'smooth', block: 'start' });
}

滚动到底部 ⬇️

/**
 * @description 滚动到底部
 */
function scrollToBottom(element: HTMLElement): void {
  element.scrollIntoView({ behavior: 'smooth', block: 'end' });
}

对象常用方法 📚

const obj = { a: 1, b: 2, c: 3, d: 4 };
// Object.keys()
// 将返回一个数组,包含给定对象自身可枚举属性的键
Object.keys(obj); // ['a', 'b', 'c', 'd']
// Object.values()
// 返回一个数组,包含给定对象自身所有可枚举属性的值
Object.values(obj); // [1, 2, 3, 4]
// Object.entries()
// 返回一个数组,包含给定对象自身可枚举属性的键值对
Object.entries(obj); // [['a', 1], ['b', 2], ['c', 3], ['d', 4]]
// Object.fromEntries

()
// 将键值对列表转换成对象,是 Object.entries() 的反向操作
Object.fromEntries([['a', 1], ['b', 2]]); // { a: 1, b: 2 }
// hasOwnProperty()
// 返回一个布尔值,指示对象自身属性中是否具有指定的属性(即,是否具有指定的键)
obj.hasOwnProperty('a'); // true
obj.hasOwnProperty('fff'); // false
// Object.assign()
// 用于将一个或多个源对象的全部可枚举属性的值复制到目标对象。它将返回目标对象。
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };
const result = Object.assign(target, source); // { ...target, ...source } 效果相同
console.log(result); // {a: 1, b: 4, c: 5}
复制全文 生成海报 编程 JavaScript 开发工具

推荐文章

Python 微软邮箱 OAuth2 认证 Demo
2024-11-20 15:42:09 +0800 CST
15 个你应该了解的有用 CSS 属性
2024-11-18 15:24:50 +0800 CST
禁止调试前端页面代码
2024-11-19 02:17:33 +0800 CST
Nginx 负载均衡
2024-11-19 10:03:14 +0800 CST
推荐几个前端常用的工具网站
2024-11-19 07:58:08 +0800 CST
html一个包含iPhoneX和MacBook模拟器
2024-11-19 08:03:47 +0800 CST
跟着 IP 地址,我能找到你家不?
2024-11-18 12:12:54 +0800 CST
防止 macOS 生成 .DS_Store 文件
2024-11-19 07:39:27 +0800 CST
php微信文章推广管理系统
2024-11-19 00:50:36 +0800 CST
Rust 并发执行异步操作
2024-11-18 13:32:18 +0800 CST
赚点点任务系统
2024-11-19 02:17:29 +0800 CST
CSS 中的 `scrollbar-width` 属性
2024-11-19 01:32:55 +0800 CST
纯CSS实现3D云动画效果
2024-11-18 18:48:05 +0800 CST
如何实现生产环境代码加密
2024-11-18 14:19:35 +0800 CST
nuxt.js服务端渲染框架
2024-11-17 18:20:42 +0800 CST
js一键生成随机颜色:randomColor
2024-11-18 10:13:44 +0800 CST
如何配置获取微信支付参数
2024-11-19 08:10:41 +0800 CST
CSS实现亚克力和磨砂玻璃效果
2024-11-18 01:21:20 +0800 CST
PHP 8.4 中的新数组函数
2024-11-19 08:33:52 +0800 CST
总结出30个代码前端代码规范
2024-11-19 07:59:43 +0800 CST
程序员茄子在线接单