25 个实用的 JavaScript 代码

2024-12-31 01:30:50   小编

25 个实用的 JavaScript 代码

在当今的网页开发领域,JavaScript 无疑是至关重要的编程语言。以下为您介绍 25 个实用的 JavaScript 代码示例,助您提升开发效率。

  1. 数组去重
function uniqueArray(arr) {
  return Array.from(new Set(arr));
}
  1. 数组排序
function sortArray(arr) {
  return arr.sort((a, b) => a - b);
}
  1. 字符串反转
function reverseString(str) {
  return str.split('').reverse().join('');
}
  1. 生成随机数
function generateRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min);
}
  1. 判断闰年
function isLeapYear(year) {
  return (year % 4 === 0 && year % 100!== 0) || year % 400 === 0;
}
  1. 计算阶乘
function factorial(n) {
  if (n === 0 || n === 1) {
    return 1;
  } else {
    return n * factorial(n - 1);
  }
}
  1. 检查是否为数字
function isNumber(value) {
  return!isNaN(parseFloat(value)) && isFinite(value);
}
  1. 深拷贝对象
function deepCopy(obj) {
  return JSON.parse(JSON.stringify(obj));
}
  1. 防抖函数
function debounce(func, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func(...args);
    }, delay);
  };
}
  1. 节流函数
function throttle(func, delay) {
  let lastCallTime = 0;
  return function (...args) {
    const now = new Date().getTime();
    if (now - lastCallTime >= delay) {
      func(...args);
      lastCallTime = now;
    }
  };
}
  1. 获取元素样式
function getStyle(element, property) {
  return window.getComputedStyle(element)[property];
}
  1. 平滑滚动到指定元素
function smoothScrollTo(element) {
  element.scrollIntoView({ behavior:'smooth' });
}
  1. 检测浏览器类型
function detectBrowser() {
  const userAgent = navigator.userAgent;
  if (userAgent.indexOf('Chrome')!== -1) {
    return 'Chrome';
  } else if (userAgent.indexOf('Firefox')!== -1) {
    return 'Firefox';
  } else {
    return 'Other';
  }
}
  1. 动态加载脚本
function loadScript(url, callback) {
  const script = document.createElement('script');
  script.src = url;
  script.onload = callback;
  document.head.appendChild(script);
}
  1. 图片懒加载
function lazyLoadImages() {
  const images = document.querySelectorAll('img[data-src]');
  images.forEach(image => {
    if (image.getBoundingClientRect().top < window.innerHeight && image.getBoundingClientRect().bottom >= 0) {
      image.src = image.dataset.src;
      image.removeAttribute('data-src');
    }
  });
}
  1. 日期格式化
function formatDate(date, format) {
  const options = {
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit'
  };
  return new Intl.DateTimeFormat('en-US', options).format(date);
}
  1. 字符串驼峰转下划线
function camelToSnake(str) {
  return str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
}
  1. 下划线转驼峰
function snakeToCamel(str) {
  return str.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
}
  1. 计算字符串出现次数
function countStringOccurrences(str, target) {
  return str.split(target).length - 1;
}
  1. 简单的轮播图实现
class Carousel {
  constructor(images) {
    this.images = images;
    this.currentIndex = 0;
  }

  next() {
    this.currentIndex = (this.currentIndex + 1) % this.images.length;
  }

  prev() {
    this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length;
  }

  getCurrentImage() {
    return this.images[this.currentIndex];
  }
}
  1. 本地存储操作
function setLocalStorage(key, value) {
  localStorage.setItem(key, JSON.stringify(value));
}

function getLocalStorage(key) {
  return JSON.parse(localStorage.getItem(key));
}

function removeLocalStorage(key) {
  localStorage.removeItem(key);
}
  1. 数组元素交换
function swapArrayElements(arr, index1, index2) {
  [arr[index1], arr[index2]] = [arr[index2], arr[index1]];
  return arr;
}
  1. 计算两个日期之间的天数差
function daysBetweenDates(date1, date2) {
  const oneDay = 24 * 60 * 60 * 1000;
  return Math.ceil(Math.abs((date1 - date2) / oneDay));
}
  1. 字符串截断
function truncateString(str, length) {
  return str.length > length? str.slice(0, length) + '...' : str;
}
  1. 简单的表单验证
function validateForm(form) {
  const inputs = form.querySelectorAll('input[required]');
  let valid = true;
  inputs.forEach(input => {
    if (!input.value) {
      input.classList.add('invalid');
      valid = false;
    } else {
      input.classList.remove('invalid');
    }
  });
  return valid;
}

这些实用的 JavaScript 代码涵盖了各种常见的功能和场景,希望能为您的开发工作带来便利和启发。不断探索和实践,您将能够更加熟练地运用 JavaScript 创造出更出色的网页应用。

TAGS: JavaScript 编程 JavaScript 技巧 JavaScript 实用代码 实用代码示例

欢迎使用万千站长工具!

Welcome to www.zzTool.com