30 个极具实用价值的 JavaScript 单行代码

2024-12-30 22:52:42   小编

30 个极具实用价值的 JavaScript 单行代码

在 JavaScript 的世界里,单行代码常常能以简洁高效的方式解决一些常见问题,展现出编程的魅力。以下为您列举 30 个极具实用价值的 JavaScript 单行代码示例:

  1. 数组去重 const uniqueArray = [...new Set(array)];

  2. 计算数组元素之和 const sum = array.reduce((acc, cur) => acc + cur, 0);

  3. 检查数组是否包含某个元素 const hasElement = array.includes(element);

  4. 反转字符串 const reversedString = string.split('').reverse().join('');

  5. 生成随机整数 const randomInt = Math.floor(Math.random() * (max - min + 1)) + min;

  6. 检查对象是否具有某个属性 const hasProperty = object.hasOwnProperty(property);

  7. 获取数组中的最大值 const maxValue = Math.max(...array);

  8. 获取数组中的最小值 const minValue = Math.min(...array);

  9. 从对象中获取指定属性的值 const propertyValue = object[property];

  10. 过滤数组中的奇数 const oddNumbers = array.filter(num => num % 2!== 0);

  11. 过滤数组中的偶数 const evenNumbers = array.filter(num => num % 2 === 0);

  12. 检查变量是否为数字 const isNumber = typeof variable === 'number' &&!isNaN(variable);

  13. 计算字符串中某个字符出现的次数 const count = string.split(character).length - 1;

  14. 转换字符串为大写 const upperCaseString = string.toUpperCase();

  15. 转换字符串为小写 const lowerCaseString = string.toLowerCase();

  16. 截取字符串的前 n 个字符 const truncatedString = string.slice(0, n);

  17. 截取字符串的后 n 个字符 const lastNCharacters = string.slice(-n);

  18. 检查字符串是否以指定字符串开头 const startsWith = string.startsWith(substring);

  19. 检查字符串是否以指定字符串结尾 const endsWith = string.endsWith(substring);

  20. 去除字符串两端的空格 const trimmedString = string.trim();

  21. 将对象转换为数组 const objectArray = Object.entries(object);

  22. 计算两个日期之间的天数差 const daysDifference = Math.ceil(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24));

  23. 检查数组是否为空 const isEmptyArray = array.length === 0;

  24. 克隆数组 const clonedArray = [...array];

  25. 交换两个变量的值 [a, b] = [b, a];

  26. 判断变量是否为数组 const isArray = Array.isArray(variable);

  27. 获取当前日期 const currentDate = new Date();

  28. 格式化日期 const formattedDate = currentDate.toISOString().split('T')[0];

  29. 清空数组 array.length = 0;

  30. 对数组进行排序 const sortedArray = array.sort((a, b) => a - b);

这些单行代码在日常的 JavaScript 开发中能够大大提高效率,减少代码量,使您的编程更加简洁和优雅。希望您能熟练掌握并运用它们,让您的开发工作更加轻松高效。

TAGS: JavaScript 技巧 实用价值 JavaScript 实用代码 JavaScript 单行

欢迎使用万千站长工具!

Welcome to www.zzTool.com