
作者 | Fatos Morina
JavaScript 是目前最流行的程式設計語言之一,正如大多數人所說:“如果你想學一門程式設計語言,請學JavaScript。”
FreeCodeCamp的創始人 Quincy Larson 在最近的一次采訪中被問到哪種語言開發人員應該首先學習。他回答:“ JavaScript。”:
“軟體正在吞噬世界,JavaScript正在吞噬軟體。JavaScript每年都在變得越來越占主導地位,而且沒人知道最終會取代它的是什麼。" 如果你沒有充分的理由學習一種新語言(例如你的工作要求你維護非JavaScript代碼庫),那麼我的建議是着重于提高JavaScript的水準。”
聽我說這麼多,你是不是很激動呢。這裡有84個常用的JS代碼片段,友善你學習和使用。
1、all
如果數組所有元素滿足函數條件,則傳回true。調用時,如果省略第二個參數,則預設傳遞布爾值。
const all = (arr, fn = Boolean) =>
all([4, 2, 3], x x > 1); // trueall([1, 2, 3]); // true
2、allEqual
判斷數組中的元素是否都相等
const allEqual = arr arr.every(val val === arr[0]);
allEqual([1, 2, 3, 4, 5, 6]); // falseallEqual([1, 1, 1, 1]); // true
3、approximatelyEqual
此代碼示例檢查兩個數字是否近似相等,差異值可以通過傳參的形式進行設定
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
approximatelyEqual(Math.PI / 2.0, 1.5708); // true
4、arrayToCSV
此段代碼将沒有逗号或雙引号的元素轉換成帶有逗号分隔符的字元串即CSV格式識别的形式。
const arrayToCSV = (arr, delimiter = ',') =>
arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');
arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'
arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'
5、arrayToHtmlList
此段代碼将數組元素轉換成<li>标記,并将此元素添加至給定的ID元素标記内。
const arrayToHtmlList = (arr, listID) =>
(el => (
(el = document.querySelector('#' + listID)),
(el.innerHTML += arr.map(item => `<li>${item}</li>`).join(''))
))();
arrayToHtmlList(['item 1', 'item 2'], 'myListID');
6、attempt
此段代碼執行一個函數,将剩餘的參數傳回函數當參數,傳回相應的結果,并能捕獲異常。
const attempt = (fn, ...args) => {
try {
return fn(...args);
} catch (e) {
return e instanceof Error ? e : new Error(e);
}
};
var elements = attempt(function(selector) {
return document.querySelectorAll(selector);
}, '>_>');
if (elements instanceof Error) elements = []; // elements = []
7、average
此段代碼傳回兩個或多個數的平均數。
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2
8、averageBy
一個 map()函數和 reduce()函數結合的例子,此函數先通過 map() 函數将對象轉換成數組,然後在調用reduce()函數進行累加,然後根據數組長度傳回平均值。
const averageBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
arr.length;
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5
9、bifurcate
此函數包含兩個參數,類型都為數組,依據第二個參數的真假條件,将一個參數的數組進行分組,條件為真的放入第一個數組,其它的放入第二個數組。這裡運用了Array.prototype.reduce() 和 Array.prototype.push() 相結合的形式。
const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]);
// [ ['beep', 'boop', 'bar'], ['foo'] ]
10、bifurcateBy
此段代碼将數組按照指定的函數邏輯進行分組,滿足函數條件的邏輯為真,放入第一個數組中,其它不滿足的放入第二個數組 。
這裡運用了Array.prototype.reduce() 和 Array.prototype.push() 相結合的形式,基于函數過濾邏輯,通過 Array.prototype.push() 函數将其添加到數組中。
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b');
// [ ['beep', 'boop', 'bar'], ['foo'] ]
11、bottomVisible
用于檢測頁面是否滾動到頁面底部。
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
bottomVisible(); // true
12、byteSize
此代碼傳回字元串的位元組長度。這裡用到了Blob對象,Blob(Binary Large Object)對象代表了一段二進制資料,提供了一系列操作接口。其他操作二進制資料的API(比如File對象),都是建立在Blob對象基礎上的,繼承了它的屬性和方法。生成Blob對象有兩種方法:一種是使用Blob構造函數,另一種是對現有的Blob對象使用slice方法切出一部分。
const byteSize = str => new Blob([str]).size;
byteSize('😀'); // 4
byteSize('Hello World'); // 11
13、capitalize
将字元串的首字母轉成大寫,這裡主要運用到了ES6的展開文法在數組中的運用。
const capitalize = ([first, ...rest]) =>
first.toUpperCase() + rest.join('');
capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', true); // 'FooBar'
14、capitalizeEveryWord
将一個句子中每個單詞首字母轉換成大寫字母,這裡中要運用了正規表達式進行替換。
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
capitalizeEveryWord('hello world!'); // 'Hello World!'
15、castArray
此段代碼将非數值的值轉換成數組對象。
const castArray = val => (Array.isArray(val) ? val : [val]);
castArray('foo'); // ['foo']
castArray([1]); // [1]
16、compact
将數組中移除值為 false 的内容。
const compact = arr => arr.filter(Boolean);
compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]);
// [ 1, 2, 3, 'a', 's', 34 ]
17、countOccurrences
統計數組中某個值出現的次數。
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
18、Create Directory
此代碼段使用 existSync() 檢查目錄是否存在,然後使用 mkdirSync() 建立目錄(如果不存在)。
const fs = require('fs');
const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
createDirIfNotExists('test');
// creates the directory 'test', if it doesn't exist
19、currentURL
傳回目前通路的 URL 位址。
const currentURL = () => window.location.href;
currentURL(); // 'https://medium.com/@fatosmorina'
20、dayOfYear
傳回目前是今年的第幾天
const dayOfYear = date =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date()); // 272
21、decapitalize
将字元串的首字母轉換成小寫字母。
const decapitalize = ([first, ...rest]) =>
first.toLowerCase() + rest.join('')
decapitalize('FooBar'); // 'fooBar'
22、deepFlatten
通過遞歸的形式,将多元數組展平成一維數組。
const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
23、default
去重對象的屬性,如果對象中含有重複的屬性,以前面的為準。
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }
24、defer
延遲函數的調用,即異步調用函數。
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
25、degreesToRads
此段代碼将标準的度數,轉換成弧度。
const degreesToRads = deg => (deg * Math.PI) / 180.0;
degreesToRads(90.0); // ~1.5708
26、difference
此段代碼查找兩個給定數組的差異,查找出前者數組在後者數組中不存在元素。
const difference = (a, b) => {
const s = new Set(b);
return a.filter(x => !s.has(x));
};
difference([1, 2, 3], [1, 2, 4]); // [3]
27、differenceBy
通過給定的函數來處理需要對比差異的數組,查找出前者數組在後者數組中不存在元素。
const differenceBy = (a, b, fn) => {
const s = new Set(b.map(fn));
return a.filter(x => !s.has(fn(x)));
};
differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2]
differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [ { x: 2 } ]
28、differenceWith
此段代碼按照給定函數邏輯篩選需要對比差異的數組,查找出前者數組在後者數組中不存在元素。
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b));
// [1, 1.2]
29、digitize
将輸入的數字拆分成單個數字組成的數組。
const digitize = n => [...`${n}`].map(i => parseInt(i));
digitize(431); // [4, 3, 1]
30、distance
計算兩點之間的距離
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
distance(1, 1, 2, 3); // 2.23606797749979
31、drop
此段代碼将給定的數組從左邊開始删除 n 個元素
const drop = (arr, n = 1) => arr.slice(n);
drop([1, 2, 3]); // [2,3]
drop([1, 2, 3], 2); // [3]
drop([1, 2, 3], 42); // []
32、dropRight
此段代碼将給定的數組從右邊開始删除 n 個元素
const dropRight = (arr, n = 1) => arr.slice(0, -n);
dropRight([1, 2, 3]); // [1,2]
dropRight([1, 2, 3], 2); // [1]
dropRight([1, 2, 3], 42); // []
33、dropRightWhile
此段代碼将給定的數組按照給定的函數條件從右開始删除,直到目前元素滿足函數條件為True時,停止删除,并傳回數組剩餘元素。
const dropRightWhile = (arr, func) => {
while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);
return arr;
};
dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]
34、dropWhile
按照給的的函數條件篩選數組,不滿足函數條件的将從數組中移除。
const dropWhile = (arr, func) => {
while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
return arr;
};
dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]
35、elementContains
接收兩個DOM元素對象參數,判斷後者是否是前者的子元素。
const elementContains = (parent, child) => parent !== child && parent.contains(child);
elementContains(document.querySelector('head'), document.querySelector('title')); // true
elementContains(document.querySelector('body'), document.querySelector('body')); // false
36、filterNonUnique
移除數組中重複的元素
const filterNonUnique = arr [ …new Set(arr)];
filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]
37、findKey
按照給定的函數條件,查找第一個滿足條件對象的鍵值。
const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));
findKey(
{
barney: { age: 36, active: true },
fred: { age: 40, active: false },
pebbles: { age: 1, active: true }
},
o => o['active']
); // 'barney'
38、findLast
按照給定的函數條件篩選數組,将最後一個滿足條件的元素進行删除。
const findLast = (arr, fn) =>
findLast([1, 2, 3, 4], n n % 2 === 1); // 3
39、flatten
按照指定數組的深度,将嵌套數組進行展平。
const flatten = (arr, depth = 1) =>
(a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
40、forEachRight
按照給定的函數條件,從數組的右邊往左依次進行執行。
const forEachRight = (arr, callback) =>
arr
0)
.reverse()
.forEach(callback);
forEachRight([1, 2, 3, 4], val console.log(val)); // '4', '3', '2', '1'
41、forOwn
此段代碼按照給定的函數條件,支援三個參數作為輸入(值、鍵、對象本身),進行疊代對象。
const forOwn = (obj, fn) => Object.keys(obj).forEach(key
forOwn({ foo: 'bar', a: 1 }, v console.log(v)); // 'bar', 1
42、functionName
此段代碼輸出函數的名稱。
const functionName = fn => (console.debug(fn.name), fn);
functionName(Math.max); // max (logged in debug channel of console)
43、getColonTimeFromDate
此段代碼從Date對象裡擷取目前時間。
const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
getColonTimeFromDate(new Date()); // "08:38:00"
44、getDaysDiffBetweenDates
此段代碼傳回兩個日期之間相差多少天。
const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / (1000 * 3600 * 24);
getDaysDiffBetweenDates(new Date('2019-01-13'), new Date('2019-01-15')); // 2
45、getStyle
此代碼傳回DOM元素節點對應的屬性值。
const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];
getStyle(document.querySelector('p'), 'font-size'); // '16px'
46、getType
此段代碼的主要功能就是傳回資料的類型。
const getType = v =>
v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
getType(new Set([1, 2, 3])); // 'set'
47、hasClass
此段代碼傳回DOM元素是否包含指定的Class樣式。
const hasClass = (el, className) => el.classList.contains(className);
hasClass(document.querySelector('p.special'), 'special'); // true
48、head
此段代碼輸出數組的第一個元素。
const head = arr => arr[0];
head([1, 2, 3]); // 1
49、hide
此段代碼隐藏指定的DOM元素。
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
此段代碼的功能主要是在給定的DOM節點後插入新的節點内容
const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);
insertAfter(document.getElementById('myId'), '<p>after</p>'); // <div id="myId">...</div> <p>after</p>
54、insertBefore
此段代碼的功能主要是在給定的DOM節點前插入新的節點内容
const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);
insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id="myId">...</div>
55、intersection
此段代碼傳回兩個數組元素之間的交集。
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]
56、intersectionBy
按照給定的函數處理需要對比的數組元素,然後根據處理後的數組,找出交集,最後從第一個數組中将對應的元素輸出。
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]
57、intersectionBy
按照給定的函數對比兩個數組的差異,然後找出交集,最後從第一個數組中将對應的元素輸出。
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]
58、is
此段代碼用于判斷資料是否為指定的資料類型,如果是則傳回true。
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); // falseisBoolean(false); // true
64、getColonTimeFromDate
用于判斷程式運作環境是否在浏覽器,這有助于避免在node環境運作前端子產品時出錯。
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以及類型是否為對象。
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
用于判斷參數的值是否是 Symbol 類型。
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
此函數功能用于比較兩個對象,以确定第一個對象是否包含與第二個對象相同的屬性與值。
onst 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 位最大的數。
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