127個常用的JS代碼片段,每段代碼花30秒就能看懂(三)

大家好,在前兩篇文章裡 和 ,我分享了前42段代碼,今天我繼續分享第三部分,希望對你的日常工作有所幫助。


127個常用的JS代碼片段,每段代碼花30秒就能看懂(三)

43、getColonTimeFromDate

此段代碼從Date對象裡獲取當前時間。

<code>const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);getColonTimeFromDate(new Date()); // "08:38:00"/<code>

44、getDaysDiffBetweenDates

此段代碼返回兩個日期之間相差多少天

<code>const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>  (dateFinal - dateInitial) / (1000 * 3600 * 24);  getDaysDiffBetweenDates(new Date('2019-01-13'), new Date('2019-01-15')); // 2/<code>

45、getStyle

此代碼返回DOM元素節點對應的屬性值。

<code>const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];getStyle(document.querySelector('p'), 'font-size'); // '16px'/<code>

46、getType

此段代碼的主要功能就是返回數據的類型。

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

47、hasClass

此段代碼返回DOM元素是否包含指定的Class樣式。

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

48、head

此段代碼輸出數組的第一個元素。

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

49、hide

此段代碼隱藏指定的DOM元素。

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

50、httpsRedirect

此段代碼的功能就是將http網址重定向https網址。

<code>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/<code>

51、indexOfAll

此代碼可以返回數組中某個值對應的所有索引值,如果不包含該值,則返回一個空數組。

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

52、initial

此段代碼返回數組中除最後一個元素的所有元素

<code>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]/<code>

53、insertAfter

此段代碼的功能主要是在給定的DOM節點後插入新的節點內容

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

after

'); //
...

after

/<code>

54、insertBefore

此段代碼的功能主要是在給定的DOM節點前插入新的節點內容

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

before

'); //

before

...
/<code>

55、intersection

此段代碼返回兩個數組元素之間的交集。

<code>const intersection = (a, b) => {  const s = new Set(b);  return a.filter(x => s.has(x));};intersection([1, 2, 3], [4, 3, 2]); // [2, 3]/<code>

56、intersectionBy

按照給定的函數處理需要對比的數組元素,然後根據處理後的數組,找出交集,最後從第一個數組中將對應的元素輸出。

<code>const intersectionBy = (a, b, fn) => {  const s = new Set(b.map(fn));  return a.filter(x => s.has(fn(x)));};intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]/<code>

57、intersectionBy

按照給定的函數對比兩個數組的差異,然後找出交集,最後從第一個數組中將對應的元素輸出。

<code>const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);intersectionWith([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]/<code>

58、is

此段代碼用於判斷數據是否為指定的數據類型,如果是則返回true。

<code>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/<code>

59、isAfterDate

接收兩個日期類型的參數,判斷前者的日期是否晚於後者的日期。

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

60、isAnagram

用於檢測兩個單詞是否相似。

<code>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/<code>

61、isArrayLike

此段代碼用於檢測對象是否為類數組對象,是否可迭代。

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

62、isBeforeDate

接收兩個日期類型的參數,判斷前者的日期是否早於後者的日期。

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

63、isBoolean

此段代碼用於檢查參數是否為布爾類型。

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

小節

今天的內容就和大家分享到這裡,感謝你的閱讀,如果你喜歡我的分享,麻煩給個關注、點贊加轉發哦,你的支持,就是我分享的動力,後續會持續分享剩餘的代碼片段,歡迎持續關注。

本文原作者:Fatos Morina

來源網站:medium

注:並非直譯


分享到:


相關文章: