本文共 8233 字,大约阅读时间需要 27 分钟。
i英文 | https://betterprogramming.pub/127-helpful-javascript-snippets-you-can-learn-in-30-seconds-or-less-part-1-of-6-bc2bc890dfe5
翻译 | 杨小二
此代码段可用于获取值的类型。
const getType = v => v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();getType(new Set([1, 2, 3])); // 'set'
此代码段检查元素是否具有特定类。
const hasClass = (el, className) => el.classList.contains(className);hasClass(document.querySelector('p.special'), 'special'); // true
此代码段返回head列表的 。
const head = arr => arr[0];head([1, 2, 3]); // 1
此代码段可用于隐藏指定的所有元素。
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));hide(document.querySelectorAll('img')); // Hides all elements on the page
此代码段可用于在特定域中从 HTTP 重定向到 HTTPS。
const httpsRedirect = () => { if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);};httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com
此代码段可用于获取数组中某个值的所有索引,如果该值未包含在其中,则返回一个空数组。
const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]indexOfAll([1, 2, 3], 4); // []
此代码段返回数组中除最后一个元素之外的所有元素。
const initial = arr => arr.slice(0, -1);initial([1, 2, 3]); // [1,2]const initial = arr => arr.slice(0, -1);initial([1, 2, 3]); // [1,2]
此代码段可用于在特定元素的末尾插入 HTML 字符串。
const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);insertAfter(document.getElementById('myId'), 'after
'); //...after
此代码段可用于在特定元素之前插入 HTML 字符串。
const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);insertBefore(document.getElementById('myId'), 'before
'); //before
...
此代码段可用于获取包含在其他两个数组中的元素的数组。
const interp = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x));};interp([1, 2, 3], [4, 3, 2]); // [2, 3]
在对两个数组的每个元素执行特定函数后,此代码段可用于返回存在于两个数组中的元素列表。
const interpBy = (a, b, fn) => { const s = new Set(b.map(fn)); return a.filter(x => s.has(fn(x)));};interpBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]
此代码段可用于通过使用比较器函数返回存在于两个数组中的元素列表。
const interpWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);interpWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1.5, 3, 0]
此代码段可用于检查值是否属于特定类型。
const is = (type, val) => ![, null].includes(val) && val.constructor === type;is(Array, [1]); // trueis(ArrayBuffer, new ArrayBuffer()); // trueis(Map, new Map()); // trueis(RegExp, /./g); // trueis(Set, new Set()); // trueis(WeakMap, new WeakMap()); // trueis(WeakSet, new WeakSet()); // trueis(String, ''); // trueis(String, new String('')); // trueis(Number, 1); // trueis(Number, new Number(1)); // trueis(Boolean, true); // trueis(Boolean, new Boolean(true)); // true
此代码段可用于检查某个日期是否在另一个日期之后。
const isAfterDate = (dateA, dateB) => dateA > dateB;isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true
此代码段可用于检查特定字符串是否是另一个字符串的字谜。
const isAnagram = (str1, str2) => { const normalize = str => str .toLowerCase() .replace(/[^a-z0-9]/gi, '') .split('') .sort() .join(''); return normalize(str1) === normalize(str2);};isAnagram('iceman', 'cinema'); // true
此代码段可用于检查提供的参数是否像数组一样可迭代。
const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function';isArrayLike(document.querySelectorAll('.className')); // trueisArrayLike('abc'); // trueisArrayLike(null); // false
此代码段可用于检查某个日期是否在另一个日期之前。
const isBeforeDate = (dateA, dateB) => dateA < dateB;isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true
此代码段可用于检查参数是否为布尔值。
const isBoolean = val => typeof val === 'boolean';isBoolean(null); // falseisBoolean(false); // true
此代码段可用于确定当前运行时环境是否为浏览器。这有助于避免在服务器(节点)上运行前端模块时出错。
const isBrowser = () => ![typeof window, typeof document].includes('undefined');isBrowser(); // true (browser)isBrowser(); // false (Node)
此代码段可用于确定浏览器选项卡是否获得焦点。
const isBrowserTabFocused = () => !document.hidden;isBrowserTabFocused(); // true
此代码段可用于确定字符串是否为小写。
const isLowerCase = str => str === str.toLowerCase();isLowerCase('abc'); // trueisLowerCase('a3@$'); // trueisLowerCase('Ab4'); // false
此代码段可用于检查值是否为null或undefined。
const isNil = val => val === undefined || val === null;isNil(null); // trueisNil(undefined); // true
此代码段可用于检查值是否为null。
const isNull = val => val === null;isNull(null); // true
此代码段可用于检查提供的值是否为数字。
function isNumber(n) { return !isNaN(parseFloat(n)) && isFinite(n);}isNumber('1'); // falseisNumber(1); // true
此代码段可用于检查提供的值是否为对象。它使用 Object 构造函数为给定值创建对象包装器。
如果它已经是一个对象,则将返回与给定值对应的对象类型。否则,将返回一个新对象。
const isObject = obj => obj === Object(obj);isObject([1, 2, 3, 4]); // trueisObject([]); // trueisObject(['Hello!']); // trueisObject({ a: 1 }); // trueisObject({}); // trueisObject(true); // false
此代码段可用于检查值是否不为 null ,以及其 typeof 是否为“对象”。
const isObjectLike = val => val !== null && typeof val === 'object';isObjectLike({}); // trueisObjectLike([1, 2, 3]); // trueisObjectLike(x => x); // falseisObjectLike(null); // false
此代码段检查值是否由 Object 构造函数创建的对象。
const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;isPlainObject({ a: 1 }); // trueisPlainObject(new Map()); // false
此代码段检查对象是否看起来像Promise.
const isPromiseLike = obj => obj !== null && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';isPromiseLike({ then: function() { return ''; }}); // trueisPromiseLike(null); // falseisPromiseLike({}); // false
此代码段可用于检查两个日期是否相等。
const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString();isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 20)); // true
此代码段可用于检查参数是否为字符串。
const isString = val => typeof val === 'string';isString('10'); // true
此代码段可用于检查参数是否为符号。
const isSymbol = val => typeof val === 'symbol';isSymbol(Symbol('x')); // true
此代码段可用于检查值是否为undefined。
const isUndefined = val => val === undefined;isUndefined(undefined); // true
此代码段可用于检查字符串是否为大写。
const isUpperCase = str => str === str.toUpperCase();isUpperCase('ABC'); // trueisLowerCase('A3@$'); // trueisLowerCase('aB4'); // false
此代码段可用于检查字符串是否为有效的 JSON。
const isValidJSON = str => { try { JSON.parse(str); return true; } catch (e) { return false; }};isValidJSON('{"name":"Adam","age":20}'); // trueisValidJSON('{"name":"Adam",age:"20"}'); // falseisValidJSON(null); // true
此代码段返回数组的最后一个元素。
const last = arr => arr[arr.length - 1];last([1, 2, 3]); // 3
此代码段比较两个对象以确定第一个对象是否包含与第二个对象相同的属性值。
const matches = (obj, source) => Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // truematches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true }); // false
此代码段可用于获取最新日期。
const maxDate = (...dates) => new Date(Math.max.apply(null, ...dates));const array = [ new Date(2017, 4, 13), new Date(2018, 2, 12), new Date(2016, 0, 10), new Date(2016, 0, 9)];maxDate(array); // 2018-03-11T22:00:00.000Z
此代码段返回n列表中最大的元素。如果n大于或等于列表的长度,则返回原始列表(按降序排序)。
const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);maxN([1, 2, 3]); // [3]maxN([1, 2, 3], 2); // [3,2]
此代码段可用于获取最早日期。
const minDate = (...dates) => new Date(Math.min.apply(null, ...dates));const array = [ new Date(2017, 4, 13), new Date(2018, 2, 12), new Date(2016, 0, 10), new Date(2016, 0, 9)];minDate(array); // 2016-01-08T22:00:00.000Z
此代码段返回n列表中的最小元素。如果n大于或等于列表的长度,则返回原始列表(按升序排序)。
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);minN([1, 2, 3]); // [1]minN([1, 2, 3], 2); // [1,2]
总结
这是一个非常长的列表,但希望它可以帮助你学习,并可以立即开始使用的东西。
祝编程愉快!
推荐阅读
学习更多技能
请点击下方公众号
转载地址:http://qwdpi.baihongyu.com/