返回

100 个常用且巧妙的 JavaScript 代码片段,让你的开发事半功倍!

前端

作为一名开发人员,我们经常会遇到各种各样的编程问题,其中一些问题可以通过现成的 JavaScript 代码片段轻松解决。这些代码片段不仅可以节省我们的时间,还可以帮助我们学习新的 JavaScript 技术和技巧。

在这篇文章中,我将为您提供 100 个常用且巧妙的 JavaScript 代码片段,涵盖各种常见开发场景。这些代码片段使用 ES6 JavaScript 编写,并经过精简和测试,以确保其兼容性和实用性。

1. 字符串处理

// 1.1 判断字符串是否为空
const isEmpty = (str) => !str || str.length === 0;

// 1.2 修剪字符串两端的空格
const trim = (str) => str.trim();

// 1.3 将字符串转换为大写
const toUpperCase = (str) => str.toUpperCase();

// 1.4 将字符串转换为小写
const toLowerCase = (str) => str.toLowerCase();

// 1.5 将字符串中的所有空格替换为连字符
const replaceAllSpacesWithHyphens = (str) => str.replace(/\s/g, '-');

// 1.6 将字符串中的所有连字符替换为空格
const replaceAllHyphensWithSpaces = (str) => str.replace(/-/g, ' ');

// 1.7 将字符串中的所有数字替换为空字符串
const removeNumbers = (str) => str.replace(/[0-9]/g, '');

// 1.8 将字符串中的所有标点符号替换为空字符串
const removePunctuation = (str) => str.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()"]/g, '');

// 1.9 将字符串中的所有特殊字符替换为空字符串
const removeSpecialCharacters = (str) => str.replace(/[^\w\s]/g, '');

// 1.10 将字符串中的所有 HTML 实体转换为相应的字符
const decodeHtmlEntities = (str) => {
  const textarea = document.createElement('textarea');
  textarea.innerHTML = str;
  return textarea.value;
};

2. 数组操作

// 2.1 检查数组是否为空
const isEmpty = (arr) => !arr || arr.length === 0;

// 2.2 将数组中的所有元素转换为字符串
const toString = (arr) => arr.join(', ');

// 2.3 将数组中的所有元素转换为数字
const toNumber = (arr) => arr.map(Number);

// 2.4 将数组中的所有元素转换为布尔值
const toBoolean = (arr) => arr.map(Boolean);

// 2.5 将数组中的所有元素转换为对象
const toObject = (arr) => arr.map(JSON.parse);

// 2.6 将数组中的所有元素转换为 JSON 字符串
const toJson = (arr) => arr.map(JSON.stringify);

// 2.7 将数组中的所有重复元素删除
const removeDuplicates = (arr) => [...new Set(arr)];

// 2.8 将数组中的所有空元素删除
const removeEmptyElements = (arr) => arr.filter((item) => item !== null && item !== undefined && item !== '');

// 2.9 将数组中的所有 NaN 元素删除
const removeNaNs = (arr) => arr.filter((item) => !isNaN(item));

// 2.10 将数组中的所有 Infinity 元素删除
const removeInfinitys = (arr) => arr.filter((item) => !isFinite(item));

3. 函数编写

// 3.1 创建一个函数,该函数接受两个参数并返回它们的和
const add = (a, b) => a + b;

// 3.2 创建一个函数,该函数接受一个参数并返回其平方值
const square = (x) => x * x;

// 3.3 创建一个函数,该函数接受一个数组并返回数组中的最大值
const max = (arr) => Math.max(...arr);

// 3.4 创建一个函数,该函数接受一个数组并返回数组中的最小值
const min = (arr) => Math.min(...arr);

// 3.5 创建一个函数,该函数接受一个数组并返回数组中的平均值
const average = (arr) => arr.reduce((a, b) => a + b, 0) / arr.length;

// 3.6 创建一个函数,该函数接受一个字符串并返回字符串中的元音字母的数量
const countVowels = (str) => str.match(/[aeiou]/gi).length;

// 3.7 创建一个函数,该函数接受一个字符串并返回字符串中的辅音字母的数量
const countConsonants = (str) => str.match(/[bcdfghjklmnpqrstvwxyz]/gi).length;

// 3.8 创建一个函数,该函数接受一个数组并返回数组中出现次数最多的元素
const mostFrequent = (arr) => {
  const counts = {};
  arr.forEach((item) => {
    if (counts[item]) {
      counts[item]++;
    } else {
      counts[item] = 1;
    }
  });
  const maxCount = Math.max(...Object.values(counts));
  const mostFrequentItems = [];
  for (const item in counts) {
    if (counts[item] === maxCount) {
      mostFrequentItems.push(item);
    }
  }
  return mostFrequentItems;
};

// 3.9 创建一个函数,该函数接受一个数组并返回数组中的众数
const median = (arr) => {
  const sortedArr = arr.sort((a, b) => a - b);
  const middleIndex = Math.floor(sortedArr.length / 2);
  if (sortedArr.length % 2 === 0) {
    return (sortedArr[middleIndex] + sortedArr[middleIndex - 1]) / 2;
  } else {
    return sortedArr[middleIndex];
  }
};

// 3.10 创建一个函数,该函数接受一个数组并返回数组中的四分位数