技术文摘
38 个实用的 JavaScript 单行代码集锦
38 个实用的 JavaScript 单行代码集锦
在 JavaScript 编程的世界里,巧妙运用单行代码可以极大地提高开发效率和代码的简洁性。以下为您呈现 38 个实用的 JavaScript 单行代码示例,希望能为您的编程之旅带来便利。
1. 数组去重
const uniqueArray = [...new Set(array)];
2. 计算数组元素之和
const sum = array.reduce((a, b) => a + b, 0);
3. 检查数组是否包含某个元素
const hasElement = array.includes(element);
4. 获取对象的键数组
const keys = Object.keys(obj);
5. 获取对象的值数组
const values = Object.values(obj);
6. 交换两个变量的值
[a, b] = [b, a];
7. 生成指定范围内的随机整数
const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
8. 反转字符串
const reversedString = string.split('').reverse().join('');
9. 检查变量是否为数字
const isNumber = typeof variable === 'number' &&!isNaN(variable);
10. 检查变量是否为数组
const isArray = Array.isArray(variable);
11. 从数组中删除特定元素
const newArray = array.filter(item => item!== element);
12. 计算字符串中某个字符出现的次数
const count = string.split('').filter(c => c === char).length;
13. 判断一个数是否为偶数
const isEven = num % 2 === 0;
14. 判断一个数是否为奇数
const isOdd = num % 2!== 0;
15. 对数组进行排序
const sortedArray = array.sort((a, b) => a - b);
16. 计算数组中最大值
const maxValue = Math.max(...array);
17. 计算数组中最小值
const minValue = Math.min(...array);
18. 格式化数字为货币格式
const formattedCurrency = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(number);
19. 截取字符串
const slicedString = string.slice(start, end);
20. 检查字符串是否以某个子串开头
const startsWithSubstring = string.startsWith(substring);
21. 检查字符串是否以某个子串结尾
const endsWithSubstring = string.endsWith(substring);
22. 首字母大写
const capitalizedString = string.charAt(0).toUpperCase() + string.slice(1);
23. 克隆对象
const clonedObject = {...obj };
24. 合并对象
const mergedObject = {...obj1,...obj2 };
25. 清空数组
array.length = 0;
26. 数组扁平化
const flattenedArray = array.flat();
27. 检查对象是否为空
const isEmptyObject = Object.keys(obj).length === 0 && obj.constructor === Object;
28. 获取当前日期
const currentDate = new Date();
29. 获取当前日期的字符串格式
const dateString = currentDate.toISOString().split('T')[0];
30. 延迟执行函数
setTimeout(() => { /* 函数体 */ }, delay);
31. 间隔执行函数
setInterval(() => { /* 函数体 */ }, interval);
32. 从 URL 中获取参数
const params = new URLSearchParams(window.location.search);
33. 生成随机字符串
const randomString = Math.random().toString(36).substring(2, 10);
34. 字符串替换
const replacedString = string.replace(oldValue, newValue);
35. 数组元素随机排序
array.sort(() => Math.random() - 0.5);
36. 检查是否为正数
const isPositive = num > 0;
37. 检查是否为负数
const isNegative = num < 0;
38. 检查是否为整数
const isInteger = Number.isInteger(num);
这些单行代码在日常的 JavaScript 开发中经常会用到,熟练掌握它们可以让您的代码更加简洁高效。不断探索和实践,您将发现更多 JavaScript 的奇妙之处。
TAGS: JavaScript 编程 JavaScript 单行代码 实用的 JavaScript JavaScript 集锦
- PHP 中的代理模式:结构型模式解析
- JS 正则实现对 Markdown 中图片标签的匹配
- PHP 结构型模式中的享元模式剖析
- PHP 中的责任链行为型模式
- 正则表达式用于规范 input 框固定输入值的格式(金额、特殊字符)
- golang 正则表达式浅析
- 浅析 PHP 设计模式之中介者模式
- PHP 面向对象程序设计概述
- PHP 中的命令模式设计
- 浅析 PHP 设计模式中的解释器模式
- .Net 反向代理组件 Yarp 的详细用法
- 浅析 PHP 设计模式中的迭代器模式
- 浅析 PHP 设计模式中的观察者模式
- xpath 选择器、PyQuery 与正则表达式的格式清理工具深度剖析
- Asp.net Core 项目的 HTTPS 支持配置