
本文将分享一些精巧的JavaScript单行代码,让你的代码更简洁高效。
1. 交换两个变量无需临时变量
<code class="javascript">[a, b] = [b, a];</code>
利用数组解构赋值巧妙地交换变量值。
2. 检查数字是否为偶数
立即学习“Java免费学习笔记(深入)”;
<code class="javascript">const isEven = n => !(n & 1);</code>
使用位运算符高效判断奇偶性。
3. 反转字符串
<code class="javascript">const reverseString = str => [...str].reverse().join('');</code>利用展开运算符、reverse()方法和join()方法简洁地反转字符串。
4. 生成随机十六进制颜色
<code class="javascript">const randomColor = () => `#${Math.floor(Math.random()*0xffffff).toString(16).padStart(6, '0')}`;</code>生成随机数,转换为十六进制,并确保长度为6位。
5. 获取数组的最后一项
<code class="javascript">const lastItem = arr => arr.at(-1);</code>
使用at()方法直接获取数组最后一项。
6. 展开嵌套数组
<code class="javascript">const flatArray = arr => arr.flat(Infinity);</code>
使用flat()方法递归展开所有嵌套数组。
7. 将字符串转换为数字
<code class="javascript">const toNumber = str => +str;</code>
使用一元加号运算符将字符串转换为数字。
8. 从数组中删除重复项
<code class="javascript">const uniqueArray = arr => [...new Set(arr)];</code>
利用Set对象的特性去除数组中的重复元素。
9. 查找两个数组的交集
<code class="javascript">const intersection = (a, b) => a.filter(x => b.includes(x));</code>
使用filter()方法和includes()方法查找两个数组的交集。
10. 洗牌数组
<code class="javascript">const shuffle = arr => arr.sort(() => Math.random() - 0.5);</code>
使用sort()方法和随机数进行简单的数组洗牌(并非最优算法)。
11. 获取当前时间戳
<code class="javascript">const timestamp = () => Date.now();</code>
使用Date.now()方法获取当前时间戳。
12. 短路默认值
<code class="javascript">const greet = name => name || 'guest';</code>
使用逻辑或运算符设置默认值。
13. 统计数组中元素出现的次数
<code class="javascript">const countOccurrences = (arr, val) => arr.reduce((a, v) => v === val ? a + 1 : a, 0);</code>
使用reduce()方法统计元素出现的次数。
14. 从数组中获取随机元素
<code class="javascript">const randomItem = arr => arr[Math.floor(Math.random() * arr.length)];</code>
使用Math.random()方法随机选择数组元素。
15. 将RGB转换为十六进制
<code class="javascript">const rgbToHex = (r, g, b) => `#${((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1)}`;</code>使用位运算和toString(16)方法将RGB转换为十六进制。
16. 检查字符串是否为回文
<code class="javascript">const isPalindrome = str => str === [...str].reverse().join('');</code>将字符串反转并与原字符串比较。
17. 将布尔值转换为数字
<code class="javascript">const boolToNumber = bool => +bool;</code>
使用一元加号运算符将true转换为1,false转换为0。
18. 将字符串首字母大写
<code class="javascript">const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);</code>
将字符串首字母大写。
19. 从字符串中删除空格
<code class="javascript">const trimSpaces = str => str.replace(/\s+/g, '');</code>
使用正则表达式删除字符串中的所有空格。
20. 生成随机布尔值
<code class="javascript">const randomBoolean = () => Math.random() >= 0.5;</code>
根据随机数生成true或false。
结论
JavaScript单行代码可以使代码更简洁,但可读性和可维护性始终优先。 选择适合场景的代码风格,才能写出既高效又易于理解的代码。
以上就是JavaScript单线会让您看起来像专业人士的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号