技术文摘
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 集锦
- Redis于分布式存储及内容分发里的应用实战
- Redis应用之文章点赞功能设计实例分享
- Redis在社交媒体平台设计中的应用实例分享
- 分布式任务调度中 Redis 的应用实战
- 分布式服务治理中Redis的运用
- 基于Redis的分布式任务调度应用实践
- 分布式架构里Redis的角色及应用
- Redis分布式事务可靠性与一致性之对比
- 云原生应用里Redis的服务治理与服务网格
- Redis 作为流式数据处理平台的实时计算能力比较
- Redis分布式事务多节点部署的详细要点
- 深度解析:Redis如何实现分布式任务执行的多语言支持
- Redis分布式事务性能测试及结果剖析
- 爬虫数据处理中Redis的应用实战
- 容器存储与备份场景下Redis的应用实践