127个超级实用的JavaScript 代码片段,你千万要收藏好(中)

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

翻译 | 杨小二

接上前面的上篇的内容,如果还没有看过的小伙伴们,可以点击《127个超级实用的JavaScript 代码片段,你千万要收藏好(上)》去看一下,今天我们开始中篇内容。

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 <img> 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'), '<p>after</p>'); // <div id="myId">...</div> <p>after</p>

54、insertBefore

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

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


insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id="myId">...</div>

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]); // true
is(ArrayBuffer, new ArrayBuffer()); // true
is(Map, new Map()); // true
is(RegExp, /./g); // true
is(Set, new Set()); // true
is(WeakMap, new WeakMap()); // true
is(WeakSet, new WeakSet()); // true
is(String, ''); // true
is(String, new String('')); // true
is(Number, 1); // true
is(Number, new Number(1)); // true
is(Boolean, true); // true
is(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')); // true
isArrayLike('abc'); // true
isArrayLike(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); // false
isBoolean(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'); // true
isLowerCase('a3@$'); // true
isLowerCase('Ab4'); // false

67、 isNil

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

const isNil = val => val === undefined || val === null;


isNil(null); // true
isNil(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'); // false
isNumber(1); // true

70、 isObject

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

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

const isObject = obj => obj === Object(obj);


isObject([1, 2, 3, 4]); // true
isObject([]); // true
isObject(['Hello!']); // true
isObject({ a: 1 }); // true
isObject({}); // true
isObject(true); // false

71、 isObjectLike

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

const isObjectLike = val => val !== null && typeof val === 'object';


isObjectLike({}); // true
isObjectLike([1, 2, 3]); // true
isObjectLike(x => x); // false
isObjectLike(null); // false

72、 isPlainObject

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

const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;


isPlainObject({ a: 1 }); // true
isPlainObject(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 '';
  }
}); // true
isPromiseLike(null); // false
isPromiseLike({}); // 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'); // true
isLowerCase('A3@$'); // true
isLowerCase('aB4'); // false

79、 isValidJSON

此代码段可用于检查字符串是否为有效的 JSON。

const isValidJSON = str => {
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
};


isValidJSON('{"name":"Adam","age":20}'); // true
isValidJSON('{"name":"Adam",age:"20"}'); // false
isValidJSON(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 }); // true
matches({ 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]

总结

这是一个非常长的列表,但希望它可以帮助你学习,并可以立即开始使用的东西。

祝编程愉快!

推荐阅读

127个超级实用的JavaScript 代码片段,你千万要收藏好(上)

学习更多技能

请点击下方公众号

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值