社区精选|盘点一些好用的 JS 单行代码( 二 )


将字符串的第一个字符改为小写
const lowercaseFirst = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`; // 例子 lowercaseFirst('Hello World'); // 'hello World' 复制代码
重复一个字符串
const repeat = (str, numberOfTimes) => str.repeat(numberOfTimes); // 例子 repeat('ab', 3) // ababab 复制代码
Dates
给一个小时添加“am/pm”后缀
// `h` is an hour number between 0 and 23 const suffixAmPm = (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`; // 例子 suffixAmPm(0); // '12am' suffixAmPm(5); // '5am' suffixAmPm(12); // '12pm' suffixAmPm(15); // '3pm' suffixAmPm(23); // '11pm' 复制代码
计算两个日期之间的不同天数
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24)); // 例子 diffDays(new Date('2014-12-19'), new Date('2020-01-01')); // 1839 复制代码
检查日期是否有效
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf()); isDateValid("December 17, 1995 03:24:00"); // true 复制代码
其它
检查代码是否在Node.js中运行
const isNode = typeof process !== 'undefined' && process.versions != null &&process.versions.node != null; 复制代码
检查代码是否在浏览器中运行
const isBrowser = typeof window === 'object' && typeof document === 'object'; 复制代码
将URL参数转换为对象
const getUrlParams = (query) =>Array.from(newURLSearchParams(query)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k]? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),{}); // 例子 getUrlParams(location.search); // Get the parameters of the current URL getUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" } // Duplicate key getUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" } 复制代码
黑暗检测模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; 复制代码
拷贝到剪切板
const copyToClipboard = (text) =>navigator.clipboard.writeText(text); // 例子 copyToClipboard("Hello World"); 复制代码
将RGB转换为十六进制
const rgbToHex = (r, g, b) =>"#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); // 例子 rgbToHex(0, 51, 255); // #0033ff 复制代码
生成一个随机的十六进制颜色
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`; // 或者 const randomColor = () => `#${(~~(Math.random() * (1 << 24))).toString(16)}`; 复制代码
生成随机IP地址
const randomIp = () => Array(4).fill(0) .map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0)) .join('.'); // 例子 randomIp(); // 175.89.174.131 复制代码
使用 Node crypto 模块生成随机字符串
const randomStr = () => require('crypto').randomBytes(32).toString('hex'); 复制代码
作者:Ahmad 译者:前端小智 来源:ishadee
原文:https://javascript.plainenglish.io/17-life-saving-javascript-one-liners-part1-b0b0b32c9f61

社区精选|盘点一些好用的 JS 单行代码

文章插图
Tags:


推荐阅读