34個(gè)可以提升開發(fā)效率的JavaScript單行程序代碼片段

英文 | https://javascript.plainenglish.io/another-17-life-saving-javascript-one-liners-8c335bf73d2c
翻譯 | 楊小二
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、返回上一個(gè)頁面
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 轉(zhuǎn)換為對(duì)象
const cookies = document.cookie.split(';').map((item) => item.split('=')).reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {});// `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、將對(duì)象數(shù)組轉(zhuǎn)換為單個(gè)對(duì)象
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、按對(duì)象數(shù)組的屬性計(jì)數(shù)
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、檢查數(shù)組是否為空
const isNotEmpty = (arr) => Array.isArray(arr) && Object.keys(arr).length > 0;// ExamplesisNotEmpty([]); // falseisNotEmpty([1, 2, 3]); // true
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、從對(duì)象數(shù)組中提取屬性的值
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、反轉(zhuǎn)對(duì)象的鍵和值
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、從對(duì)象中刪除所有空和未定義的屬性
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、按屬性對(duì)對(duì)象進(jìn)行排序
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、檢查一個(gè)對(duì)象是否是一個(gè) Promise
const isPromise = (obj) =>!!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
17、檢查對(duì)象是否為數(shù)組
const isArray = (obj) => Array.isArray(obj);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、使字符串的第一個(gè)字符小寫
const lowercaseFirst = (str) => `${str.charAt(0).toLowerCase()}${str.slice(1)}`;// ExamplelowercaseFirst('Hello World'); // 'hello World'
20、重復(fù)一個(gè)字符串
const repeat = (str, numberOfTimes) => str.repeat(numberOfTimes);21、檢查字符串是否為十六進(jìn)制顏色
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、給一個(gè)小時(shí)添加“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、計(jì)算兩個(gè)日期之間的不同天數(shù)
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 中運(yùn)行
const isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;26、檢查代碼是否在瀏覽器中運(yùn)行
const isBrowser = typeof window === 'object' && typeof document === 'object';27、將 URL 參數(shù)轉(zhuǎn)換為對(duì)象
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、檢測(cè)暗模式
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;29、交換兩個(gè)變量
[a, b] = [b, a];30、復(fù)制到剪貼板
const copyToClipboard = (text) => navigator.clipboard.writeText(text);// ExamplecopyToClipboard("Hello World");
31、將 RGB 轉(zhuǎn)換為十六進(jìn)制
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);// ExamplergbToHex(0, 51, 255); // #0033ff
32、生成隨機(jī)十六進(jìn)制顏色
const randomColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;// Orconst randomColor = () => `#${(~~(Math.random() * (1 << 24))).toString(16)}`;
33、生成隨機(jī)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 模塊生成隨機(jī)字符串
const randomStr = () => require('crypto').randomBytes(32).toString('hex')學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊中國公眾號(hào)
![]()

