1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        34個單行JS代碼片段讓你的代碼更簡潔高效

        共 6643字,需瀏覽 14分鐘

         ·

        2021-10-13 16:47

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

        翻譯 | 楊小二

        在 JavaScript 的世界里,更少的代碼等于更好的明天。今天,我將向你分享 34個殺手級的JavaScript單行程序。
        其中,我將按順序列出與 DOM、數(shù)組、對象、字符串、日期和一些雜項相關(guān)的不同單行程序,希望這些列表對你有所幫助。
        現(xiàn)在,我們就開始吧。
        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 轉(zhuǎn)換為對象

        const cookies = document.cookie.split(';').map((item) => item.split('=')).reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {});
        數(shù)組
        07、比較兩個數(shù)組
        // `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、將對象數(shù)組轉(zhuǎn)換為單個對象

        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、按對象數(shù)組的屬性計數(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
        對象
        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、從對象數(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)對象的鍵和值

        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、檢查對象是否為數(shù)組

        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、計算兩個日期之間的不同天數(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 中運行

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

        26、檢查代碼是否在瀏覽器中運行

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

        27、將 URL 參數(shù)轉(zhuǎn)換為對象

        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 轉(zhuǎn)換為十六進制

        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')
        總結(jié)
        這個列表就分享到此,親愛的讀者,您的時間。如果您也能在留言區(qū)與我一起分享你的想法,我會很高興。
        最后,祝編程快樂!

        學習更多技能

        請點擊中國公眾號

        瀏覽 74
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            在线永久免费观看黄网站 | 中文无码视频在线观看 | 黄片免费观 | 我要操逼一级片 | 国內毛片 | 亚洲v欧美v日韩v国产v在线 | 精品久久久久久久 | 国产精品久免费的黄网站 | 色黄视频在线观看 | 2020天天日天天操 |