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

  • 2020 年 3 月 16 日
  • 筆記

大家好,今天我繼續給大家分享本系列文章的第五部分,希望對你的日常工作有所幫助。

85、minN

此段程式碼輸出數組中前 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]

86、negate

此函數功能將不滿足函數條件的內容篩選出來。

const negate = func => (...args) => !func(...args);    [1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0)); // [ 1, 3, 5 ]

87、nodeListToArray

此函數功能將制定的DOM節點以數組的形式輸出。

const nodeListToArray = nodeList => [...nodeList];    nodeListToArray(document.childNodes); // [ <!DOCTYPE html>, html ]

88. pad

按照指定的長度生成字元串,如果字元串長度不夠,可以按照設定的字元在其左右兩端補齊,默認為空格字元串。

const pad = (str, length, char = ' ') =>    str.padStart((str.length + length) / 2, char).padEnd(length, char);    pad('cat', 8); // '  cat   '  pad(String(42), 6, '0'); // '004200'  pad('foobar', 3); // 'foobar'

89. radsToDegrees

此函數功能將弧度轉換成度數。

const radsToDegrees = rad => (rad * 180.0) / Math.PI;    radsToDegrees(Math.PI / 2); // 90

90、randomHexColorCode

此段程式碼用於生成隨機的16進位顏色程式碼。

const randomHexColorCode = () => {    let n = (Math.random() * 0xfffff * 1000000).toString(16);    return '#' + n.slice(0, 6);  };    randomHexColorCode(); // "#e34155"

91、randomIntArrayInRange

按照指定的數字範圍隨機生成長度為 n 的數組。

const randomIntArrayInRange = (min, max, n = 1) =>    Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);    randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]

92、randomIntegerInRange

按照指定的範圍內生成一個隨機整數。

const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;    randomIntegerInRange(0, 5); // 3

93、randomNumberInRange

該程式碼段可用於返回指定範圍內的隨機數(包含小數部分)。

const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;    randomNumberInRange(2, 10); // 6.0211363285087005

94、readFileLines

此段程式碼將讀取到的文本內容,按行分割組成數組進行輸出。

const fs = require('fs');  const readFileLines = filename =>    fs      .readFileSync(filename)      .toString('UTF8')      .split('n');    let arr = readFileLines('test.txt');  console.log(arr); // ['line1', 'line2', 'line3']

95、Redirect to a URL

此函數功能將頁面導向一個指定的網站地址。

const redirect = (url, asLink = true) =>    asLink ? (window.location.href = url) : window.location.replace(url);    redirect('https://www.qianduandaren.com');

96、reverse

此段程式碼用於將一段字元串進行顛倒。

const reverseString = str => [...str].reverse().join('');    reverseString('foobar'); // 'raboof'

97、round

將小數按照指定的位數,進行四捨五入保留。

const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);    round(1.005, 2); // 1.01

98、runPromisesInSeries

通過數組的形式,連續運行多個promise。

const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());  const delay = d => new Promise(r => setTimeout(r, d));    runPromisesInSeries([() => delay(1000), () => delay(2000)]);  // Executes each promise sequentially, taking a total of 3 seconds to complete

99、sample

從數組中獲取一個隨機數。

const sample = arr => arr[Math.floor(Math.random() * arr.length)];    sample([3, 7, 9, 11]); // 9

100、sampleSize

在數組中隨機生選擇 n 個元素生成新的數組,如果n大於數組長度,則為隨機整個數組的排序。這裡使用到了 Fisher–Yates shuffle 洗牌演算法。

簡單來說 Fisher–Yates shuffle 演算法是一個用來將一個有限集合生成一個隨機排列的演算法(數組隨機排序)。這個演算法生成的隨機排列是等概率的。同時這個演算法非常高效。

更多關於 Fisher–Yates shuffle 洗牌演算法的內容,你可以點擊 閱讀原文 進行查看。

const sampleSize = ([...arr], n = 1) => {    let m = arr.length;    while (m) {      const i = Math.floor(Math.random() * m--);      [arr[m], arr[i]] = [arr[i], arr[m]];    }    return arr.slice(0, n);  };    sampleSize([1, 2, 3], 2); // [3,1]  sampleSize([1, 2, 3], 4); // [2,3,1]

101、 scrollToTop

此函數功能將頁面平滑的滾動到頁面的頂部。

const scrollToTop = () => {    const c = document.documentElement.scrollTop || document.body.scrollTop;    if (c > 0) {      window.requestAnimationFrame(scrollToTop);      window.scrollTo(0, c - c / 8);    }  };    scrollToTop();

102、serializeCookie

此段程式碼用於將 cookie 序列化成 name-value 的形式方便你存儲在 Set-Cookie 頭資訊里。

const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`;    serializeCookie('foo', 'bar'); // 'foo=bar'

103、setStyle

此段程式碼用於在相應的DOM節點添加屬性和值。

const setStyle = (el, ruleName, val) => (el.style[ruleName] = val);    setStyle(document.querySelector('p'), 'font-size', '20px');  // The first <p> element on the page will have a font-size of 20px

104、 shallowClone

此段程式碼用於淺複製一個對象。

const shallowClone = obj => Object.assign({}, obj);    const a = { x: true, y: 1 };  const b = shallowClone(a); // a !== b

105、show

段程式碼用於顯示所有指定的 DOM 元素。

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

小節

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

本文原作者:Fatos Morina 來源網站:medium 註:並非直譯