博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
127个超级实用的JavaScript 代码片段,你千万要收藏好(中)
阅读量:4115 次
发布时间:2019-05-25

本文共 8233 字,大约阅读时间需要 27 分钟。

i英文 | https://betterprogramming.pub/127-helpful-javascript-snippets-you-can-learn-in-30-seconds-or-less-part-1-of-6-bc2bc890dfe5

翻译 | 杨小二

接上前面的上篇的内容,如果还没有看过的小伙伴们,可以点击《》去看一下,今天我们开始中篇内容。

46、getType

此代码段可用于获取值的类型。

const getType = v =>  v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();getType(new Set([1, 2, 3])); // 'set'

47、hasClassi

此代码段检查元素是否具有特定类。

const hasClass = (el, className) => el.classList.contains(className);hasClass(document.querySelector('p.special'), 'special'); // true

48、head

此代码段返回head列表的 。

const head = arr => arr[0];head([1, 2, 3]); // 1

49、hide

此代码段可用于隐藏指定的所有元素。

const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));hide(document.querySelectorAll('img')); // Hides all  elements on the page

50、httpsRedirect

此代码段可用于在特定域中从 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

51、indexOfAll

此代码段可用于获取数组中某个值的所有索引,如果该值未包含在其中,则返回一个空数组。

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); // []

52、initial

此代码段返回数组中除最后一个元素之外的所有元素。

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]

53、insertAfter

此代码段可用于在特定元素的末尾插入 HTML 字符串。

const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);insertAfter(document.getElementById('myId'), '

after

'); // 
... 

after

54、insertBefore

此代码段可用于在特定元素之前插入 HTML 字符串。

const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);insertBefore(document.getElementById('myId'), '

before

'); // 

before

 
...

55、interp

此代码段可用于获取包含在其他两个数组中的元素的数组。

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]

56、interpBy

在对两个数组的每个元素执行特定函数后,此代码段可用于返回存在于两个数组中的元素列表。

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]

57、interpWith

此代码段可用于通过使用比较器函数返回存在于两个数组中的元素列表。

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]

58、is

此代码段可用于检查值是否属于特定类型。

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

59、isAfterDate

此代码段可用于检查某个日期是否在另一个日期之后。

const isAfterDate = (dateA, dateB) => dateA > dateB;isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true

60、 isAnagram

此代码段可用于检查特定字符串是否是另一个字符串的字谜。

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

61、isArrayLike

此代码段可用于检查提供的参数是否像数组一样可迭代。

const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function';isArrayLike(document.querySelectorAll('.className')); // trueisArrayLike('abc'); // trueisArrayLike(null); // false

62、 isBeforeDate

此代码段可用于检查某个日期是否在另一个日期之前。

const isBeforeDate = (dateA, dateB) => dateA < dateB;isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true

63、isBoolean

此代码段可用于检查参数是否为布尔值。

const isBoolean = val => typeof val === 'boolean';isBoolean(null); // falseisBoolean(false); // true

64、 isBrowser

此代码段可用于确定当前运行时环境是否为浏览器。这有助于避免在服务器(节点)上运行前端模块时出错。

const isBrowser = () => ![typeof window, typeof document].includes('undefined');isBrowser(); // true (browser)isBrowser(); // false (Node)

65、 isBrowserTabFocused

此代码段可用于确定浏览器选项卡是否获得焦点。

const isBrowserTabFocused = () => !document.hidden;isBrowserTabFocused(); // true

66、 isLowerCase

此代码段可用于确定字符串是否为小写。

const isLowerCase = str => str === str.toLowerCase();isLowerCase('abc'); // trueisLowerCase('a3@$'); // trueisLowerCase('Ab4'); // false

67、 isNil

此代码段可用于检查值是否为null或undefined。

const isNil = val => val === undefined || val === null;isNil(null); // trueisNil(undefined); // true

68、 isNull

此代码段可用于检查值是否为null。

const isNull = val => val === null;isNull(null); // true

69、 isNumber

此代码段可用于检查提供的值是否为数字。

function isNumber(n) {    return !isNaN(parseFloat(n)) && isFinite(n);}isNumber('1'); // falseisNumber(1); // true

70、 isObject

此代码段可用于检查提供的值是否为对象。它使用 Object 构造函数为给定值创建对象包装器。

如果它已经是一个对象,则将返回与给定值对应的对象类型。否则,将返回一个新对象。

const isObject = obj => obj === Object(obj);isObject([1, 2, 3, 4]); // trueisObject([]); // trueisObject(['Hello!']); // trueisObject({ a: 1 }); // trueisObject({}); // trueisObject(true); // false

71、 isObjectLike

此代码段可用于检查值是否不为 null ,以及其 typeof 是否为“对象”。

const isObjectLike = val => val !== null && typeof val === 'object';isObjectLike({}); // trueisObjectLike([1, 2, 3]); // trueisObjectLike(x => x); // falseisObjectLike(null); // false

72、 isPlainObject

此代码段检查值是否由 Object 构造函数创建的对象。

const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;isPlainObject({ a: 1 }); // trueisPlainObject(new Map()); // false

73、 isPromiseLike

此代码段检查对象是否看起来像Promise.

const isPromiseLike = obj =>  obj !== null &&  (typeof obj === 'object' || typeof obj === 'function') &&  typeof obj.then === 'function';isPromiseLike({  then: function() {    return '';  }}); // trueisPromiseLike(null); // falseisPromiseLike({}); // false

74、isSameDate

此代码段可用于检查两个日期是否相等。

const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString();isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 20)); // true

75、 isString

此代码段可用于检查参数是否为字符串。

const isString = val => typeof val === 'string';isString('10'); // true

76、 isSymbol

此代码段可用于检查参数是否为符号。

const isSymbol = val => typeof val === 'symbol';isSymbol(Symbol('x')); // true

77、 isUndefined

此代码段可用于检查值是否为undefined。

const isUndefined = val => val === undefined;isUndefined(undefined); // true

78、isUpperCase

此代码段可用于检查字符串是否为大写。

const isUpperCase = str => str === str.toUpperCase();isUpperCase('ABC'); // trueisLowerCase('A3@$'); // trueisLowerCase('aB4'); // false

79、 isValidJSON

此代码段可用于检查字符串是否为有效的 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

80、last

此代码段返回数组的最后一个元素。

const last = arr => arr[arr.length - 1];last([1, 2, 3]); // 3

81、matches

此代码段比较两个对象以确定第一个对象是否包含与第二个对象相同的属性值。

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

82、maxDate

此代码段可用于获取最新日期。

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

83、maxN

此代码段返回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]

84、minDate

此代码段可用于获取最早日期。

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

85、minN

此代码段返回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/

你可能感兴趣的文章
Android中启动其他Activity并返回结果
查看>>
2009年33所高校被暂停或被限制招生
查看>>
GlassFish 部署及应用入门
查看>>
iWatch报错: Authorization request cancled
查看>>
iWatch报错: Authorizationsession time out
查看>>
如何运行从网上下载的iWatch项目详细步骤.
查看>>
X-code7 beta error: warning: Is a directory
查看>>
Error: An App ID with identifier "*****" is not avaliable. Please enter a different string.
查看>>
X-code beta 开发iWatch项目,运行没有错误,但是某些操作一点就崩,而且找不错误的原因场景一
查看>>
Xcode 报错: Extra argument in call
查看>>
iTunes Connect 上传APP报错: Communication error. please use diagnostic mode to check connectivity.
查看>>
#import <Cocoa/Cocoa.h> 报错 Lexical or Preprocessor Issue 'Cocoa/Cocoa.h' file not found
查看>>
`MQTTClient (~> 0.2.6)` required by `Podfile`
查看>>
X-Code 报错 ld: library not found for -lAFNetworking
查看>>
Bitcode
查看>>
If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
查看>>
为什么新手也要学习微服务架构设计?
查看>>
专题 | 如何抢先一步拿 Offer?
查看>>
那些拿到腾讯、阿里等大厂offer的人,都有这个共同点
查看>>
陆奇、雷军、熊晓鸽聊疫情后的创业风口
查看>>