34个可以提升开发效率的JavaScript单行程序代码片段

web前端开发

共 6643字,需浏览 14分钟

 · 2021-10-09

英文 | https://javascript.plainenglish.io/another-17-life-saving-javascript-one-liners-8c335bf73d2c

翻译 | 杨小二


在 JavaScript 的世界里,更少的代码等于更好的明天。今天,我将向你分享 34个杀手级的JavaScript单行程序。
其中,我将按顺序列出与 DOM、数组、对象、字符串、日期和一些杂项相关的不同单行程序,希望这些列表对你有所帮助。
现在,我们就开始吧。
DOM
01、检查元素是否被聚焦
const hasFocus = (ele) => ele === document.activeElement;

02、获取元素的所有兄弟元素

const siblings = (ele) =>[].slice.call(ele.parentNode.children).filter((child) => child !== ele);

03、获取选定的文本

const getSelectedText = () => window.getSelection().toString();

04、返回上一个页面

history.back();// Orhistory.go(-1);

05、清除所有 cookie

const clearCookies = () => document.cookie.split(';').forEach((c) =>(document.cookie = c.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date().toUTCString()};path=/`)));

06、将 cookie 转换为对象

const cookies = document.cookie.split(';').map((item) => item.split('=')).reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {});
数组
07、比较两个数组
// `a` and `b` are arraysconst isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);// Orconst isEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);// ExamplesisEqual([1, 2, 3], [1, 2, 3]); // trueisEqual([1, 2, 3], [1, '2', 3]); // false

08、将对象数组转换为单个对象

const toObject = (arr, key) => arr.reduce((a, b) => ({ ...a, [b[key]]: b }), {});// Orconst toObject = (arr, key) => Object.fromEntries(arr.map((it) => [it[key], it]));// ExampletoObject([{ id: '1', name: 'Alpha', gender: 'Male' },{ id: '2', name: 'Bravo', gender: 'Male' },{ id: '3', name: 'Charlie', gender: 'Female' }],'id');/*{'1': { id: '1', name: 'Alpha', gender: 'Male' },'2': { id: '2', name: 'Bravo', gender: 'Male' },'3': { id: '3', name: 'Charlie', gender: 'Female' }}*/

09、按对象数组的属性计数

const countBy = (arr, prop) => arr.reduce((prev, curr) => ((prev[curr[prop]] = ++prev[curr[prop]] || 1), prev), {});// ExamplecountBy([{ branch: 'audi', model: 'q8', year: '2019' },{ branch: 'audi', model: 'rs7', year: '2020' },{ branch: 'ford', model: 'mustang', year: '2019' },{ branch: 'ford', model: 'explorer', year: '2020' },{ branch: 'bmw', model: 'x7', year: '2020' },],'branch');// { 'audi': 2, 'ford': 2, 'bmw': 1 }

10、检查数组是否为空

const isNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0;// ExamplesisNotEmpty([]); // falseisNotEmpty([1, 2, 3]); // true
对象
11、检查多个对象是否相等
const isEqual = (...objects) => objects.every((obj) => JSON.stringify(obj) === JSON.stringify(objects[0]));// ExamplesisEqual({ foo: 'bar' }, { foo: 'bar' }); // trueisEqual({ foo: 'bar' }, { bar: 'foo' }); // false

12、从对象数组中提取属性的值

const pluck = (objs, property) => objs.map((obj) => obj[property]);// Examplepluck([{ name: 'John', age: 20 },{ name: 'Smith', age: 25 },{ name: 'Peter', age: 30 },],'name');// ['John', 'Smith', 'Peter']

13、反转对象的键和值

const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {});// Orconst invert = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));// Exampleinvert({ a: '1', b: '2', c: '3' }); // { 1: 'a', 2: 'b', 3: 'c' }

14、从对象中删除所有空和未定义的属性

const removeNullUndefined = (obj) => Object.entries(obj).reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {});// Orconst removeNullUndefined = (obj) =>Object.entries(obj).filter(([_, v]) => v != null).reduce((acc, [k, v]) => ({ ...acc, [k]: v }), {});// Orconst removeNullUndefined = (obj) => Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));// ExampleremoveNullUndefined({foo: null,bar: undefined,fuzz: 42}); // { fuzz: 42 }

15、按属性对对象进行排序

const sort = (obj) =>Object.keys(obj).sort().reduce((p, c) => ((p[c] = obj[c]), p), {});// Exampleconst colors = {white: '#ffffff',black: '#000000',red: '#ff0000',green: '#008000',blue: '#0000ff',};sort(colors);/*{black: '#000000',blue: '#0000ff',green: '#008000',red: '#ff0000',white: '#ffffff',}*/

16、检查一个对象是否是一个 Promise

const isPromise = (obj) =>!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';

17、检查对象是否为数组

const isArray = (obj) => Array.isArray(obj);
字符串
18、检查路径是否是相对的
const isRelative = (path) => !/^([a-z]+:)?[\\/]/i.test(path);// ExamplesisRelative('/foo/bar/baz'); // falseisRelative('C:\\foo\\bar\\baz'); // falseisRelative('foo/bar/baz.txt'); // trueisRelative('foo.md'); // true

19、使字符串的第一个字符小写

const lowercaseFirst = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;// ExamplelowercaseFirst('Hello World'); // 'hello World'

20、重复一个字符串

const repeat = (str, numberOfTimes) => str.repeat(numberOfTimes);

21、检查字符串是否为十六进制颜色

const isHexColor = (color) => /^#([0-9A-F]{3}|[0-9A-F]{4}|[0-9A-F]{6}|[0-9A-F]{8})$/i.test(color);// ExamplesisHexColor('#012'); // trueisHexColor('#A1B2C3'); // trueisHexColor('012'); // falseisHexColor('#GHIJKL'); // false

日期

22、给一个小时添加“am/pm”后缀

// `h` is an hour number between 0 and 23const suffixAmPm = (h) => `${h % 12 === 0 ? 12 : h % 12}${h < 12 ? 'am' : 'pm'}`;// ExamplessuffixAmPm(0); // '12am'suffixAmPm(5); // '5am'suffixAmPm(12); // '12pm'suffixAmPm(15); // '3pm'suffixAmPm(23); // '11pm'

23、计算两个日期之间的不同天数

const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / (1000 * 60 * 60 * 24));// ExamplediffDays(new Date('2014-12-19'), new Date('2020-01-01')); // 1839

24、检查日期是否有效

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());isDateValid("December 17, 1995 03:24:00"); // true

其他的

25、检查代码是否在 Node.js 中运行

const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;

26、检查代码是否在浏览器中运行

const isBrowser = typeof window === 'object' && typeof document === 'object';

27、将 URL 参数转换为对象

const getUrlParams = (query) =>Array.from(new URLSearchParams(query)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),{});// ExamplesgetUrlParams(location.search); // Get the parameters of the current URLgetUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" }// Duplicate keygetUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" }

28、检测暗模式

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

29、交换两个变量

[a, b] = [b, a];

30、复制到剪贴板

const copyToClipboard = (text) => navigator.clipboard.writeText(text);// ExamplecopyToClipboard("Hello World");

31、将 RGB 转换为十六进制

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);// ExamplergbToHex(0, 51, 255); // #0033ff

32、生成随机十六进制颜色

const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;// Orconst randomColor = () => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;

33、生成随机IP地址

const randomIp = () => Array(4).fill(0).map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0)).join('.');// ExamplerandomIp(); // 175.89.174.131

34、使用 Node crypto 模块生成随机字符串

const randomStr = () => require('crypto').randomBytes(32).toString('hex')
总结
这个列表就分享到此,亲爱的读者,您的时间。如果您也能在留言区与我一起分享你的想法,我会很高兴。
最后,祝编程快乐!

学习更多技能

请点击中国公众号


浏览 24
点赞
评论
收藏
分享

手机扫一扫分享

举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

举报