我们最喜欢的 JavaScript 单行代码

2025-06-08

我们最喜欢的 JavaScript 单行代码

这些是我们最喜欢的一句话,我们已经用过它们并且忘记了它们的存在,因为它们效果很好😁。

生成随机十六进制颜色

const color = () => '#' + Math.floor(Math.random() * (0xffffff + 1)).toString(16).padEnd(6, '0');
Enter fullscreen mode Exit fullscreen mode

删除数组重复项

const removeDuplicates = arr => [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

反转字符串

const reverseString = str => [...str].reverse().join()
Enter fullscreen mode Exit fullscreen mode

清除所有cookie

注意:这种方法并非总是有效,因为 Cookie 可以设置为不从前端更改。(感谢@lukeshiru!)

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, '=;expires=${new Date(0).toUTCString()};path=/'));
Enter fullscreen mode Exit fullscreen mode

从数组中删除虚假值

const removeFalsyValues = arr => arr.filter(x=>x)

/** OR **/

const removeFalsyValues = arr => arr.filter(Boolean)
Enter fullscreen mode Exit fullscreen mode

从 URL 获取查询参数的值

传入 url 和您要查找值的参数,此函数将返回该值给您

const getQueryParam = (url, param) => new URL(url).searchParams.get(queryParam);
Enter fullscreen mode Exit fullscreen mode

复制到剪贴板

const copyToClipboard = (text) => navigator.clipboard.writeText(text);
Enter fullscreen mode Exit fullscreen mode

获取选定的文本

const getSelectedText = () => window.getSelection().toString();
Enter fullscreen mode Exit fullscreen mode

滚动到顶部

const scrollToTop = () => window.scrollTo(0, 0);
Enter fullscreen mode Exit fullscreen mode

滚动到底部

const scrollToBottom = () => window.scrollTo(0, document.body.scrollHeight);
Enter fullscreen mode Exit fullscreen mode

切换布尔值

const toggleBool = bool => !bool;
Enter fullscreen mode Exit fullscreen mode

转换华氏度/摄氏度

const cToF = (celsius) => celsius * 9/5 + 32;
const fToC = (fahrenheit) => (fahrenheit - 32) * 5/9;
Enter fullscreen mode Exit fullscreen mode

检查对象上是否存在某个属性

我知道这看起来不止一行代码,但考虑到一个对象已经存在,检查该对象的属性肯定是一行代码😁

const myObject = {
  id: 1,
  name: 'Tron',
  group: 'decepticons'
};

const isGroupExists = 'group' in myObject;
console.log(isGroupExists); // true

const isMusicExists = 'music' in myObject;
console.log(isMusicExists); // false
Enter fullscreen mode Exit fullscreen mode

谢谢

特别感谢 Fernando、José、@patricia_br@lukeshiru@lionelrowe@jonrandy对此列表进行添加和优化!

鏂囩珷鏉ユ簮锛�https://dev.to/everlyhealth/our-favorite-javascript-one-liners-3l7n
PREV
使用 Active Delivery 在 Rails 中制作用户通知
NEXT
🧑‍🎨是时候停止消费并开始创造