JavaScript 工具函數大全

目錄:

第一部分:數組第二部分:函數第三部分:字符串第四部分:對象第五部分:數字第六部分:瀏覽器操作及其它

1. 第一部分:數組

1. `all`:布爾全等判斷

const all = (arr, fn = Boolean) => arr.every(fn);

all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true

2. `allEqual`:檢查數組各項相等

const allEqual = arr => arr.every(val => val === arr[0]);

allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([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 => `${item}`).join(''))
))();

arrayToHtmlList(['item 1', 'item 2'], 'myListID');

6. `average`:平均數

const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2

7. `averageBy`:數組對象屬性平均數

此代碼段將獲取數組對象屬性的平均值

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

8.`bifurcate`:拆分斷言後的數組

可以根據每個元素返回的值,使用reduce()和push() 將元素添加到第二次參數fn中 。

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'] ]

9. `castArray`:其它類型轉數組

const castArray = val => (Array.isArray(val) ? val : [val]);

castArray('foo'); // ['foo']
castArray([1]); // [1]
castArray(1); // [1]

10. `compact`:去除數組中的無效/無用值

const compact = arr => arr.filter(Boolean);

compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]);
// [ 1, 2, 3, 'a', 's', 34 ]

11. `countOccurrences`:檢測數值出現次數

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3

12. `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]

13. `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]

14. `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 } ]

15. `dropWhile`:刪除不符合條件的值

此代碼段從數組頂部開始刪除元素,直到傳遞的函數返回為true。

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]

16. `flatten`:指定深度扁平化數組

此代碼段第二參數可指定深度。

const flatten = (arr, depth = 1) =>
arr.reduce((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]

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

18. `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]

19. `intersectionWith`:兩數組都符合條件的交集

此片段可用於在對兩個數組的每個元素執行了函數之後,返回兩個數組中存在的元素列表。

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]

20. `intersectionWith`:先比較後返回交集

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]

21. `minN`:返回指定長度的升序數組

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]

22. `negate`:根據條件反向篩選

const negate = func => (...args) => !func(...args);

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

23. `randomIntArrayInRange`:生成兩數之間指定長度的隨機數組

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 ]

24. `sample`:在指定數組中獲取隨機數

const sample = arr => arr[Math.floor(Math.random() * arr.length)];

sample([3, 7, 9, 11]); // 9

25. `sampleSize`:在指定數組中獲取指定長度的隨機數

此代碼段可用於從數組中獲取指定長度的隨機數,直至窮盡數組。
使用Fisher-Yates算法對數組中的元素進行隨機選擇。

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]

26. `shuffle`:“洗牌” 數組

此代碼段使用Fisher-Yates算法隨機排序數組的元素。

const shuffle = ([...arr]) => {
let m = arr.length;
while (m) {
const i = Math.floor(Math.random() * m--);
[arr[m], arr[i]] = [arr[i], arr[m]];
}
return arr;
};

const foo = [1, 2, 3];
shuffle(foo); // [2, 3, 1], foo = [1, 2, 3]

27. `nest`:根據`parent_id`生成樹結構(阿里一面真題)

根據每項的parent_id,生成具體樹形結構的對象。

const nest = (items, id = null, link = 'parent_id') =>
items
.filter(item => item[link] === id)
.map(item => ({ ...item, children: nest(items, item.id) }));

用法:

const comments = [
{ id: 1, parent_id: null },
{ id: 2, parent_id: 1 },
{ id: 3, parent_id: 1 },
{ id: 4, parent_id: 2 },
{ id: 5, parent_id: 4 }
];
const nestedComments = nest(comments); // [{ id: 1, parent_id: null, children: [...] }]


強烈建議去理解這個的實現,因為這是我親身遇到的阿里一面真題:

2. 第二部分:函數

1.`attempt`:捕獲函數運行異常

該代碼段執行一個函數,返回結果或捕獲的錯誤對象。

onst 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 = []

2. `defer`:推遲執行

此代碼段延遲了函數的執行,直到清除了當前調用堆棧。

const defer = (fn, ...args) => setTimeout(fn, 1, ...args);

defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'

3. `runPromisesInSeries`:運行多個`Promises`

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


//依次執行每個Promises ,總共需要3秒鐘才能完成

4. `timeTaken`:計算函數執行時間

const timeTaken = callback => {
console.time('timeTaken');
const r = callback();
console.timeEnd('timeTaken');
return r;
};

timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms

5. `createEventHub`:簡單的發佈/訂閱模式

創建一個發佈/訂閱(發佈-訂閱)事件集線,有emit,on和off方法。

使用Object.create(null)創建一個空的hub對象。emit,根據event參數解析處理程序數組,然後.forEach()通過傳入數據作為參數來運行每個處理程序。on,為事件創建一個數組(若不存在則為空數組),然後.push()將處理程序添加到該數組。off,用.findIndex()在事件數組中查找處理程序的索引,並使用.splice()刪除。

const createEventHub = () => ({
hub: Object.create(null),
emit(event, data) {
(this.hub[event] || []).forEach(handler => handler(data));
},
on(event, handler) {
if (!this.hub[event]) this.hub[event] = [];
this.hub[event].push(handler);
},
off(event, handler) {
const i = (this.hub[event] || []).findIndex(h => h === handler);
if (i > -1) this.hub[event].splice(i, 1);
if (this.hub[event].length === 0) delete this.hub[event];


}
});

用法:

const handler = data => console.log(data);
const hub = createEventHub();
let increment = 0;

// 訂閱,監聽不同事件
hub.on('message', handler);
hub.on('message', () => console.log('Message event fired'));
hub.on('increment', () => increment++);

// 發佈:發出事件以調用所有訂閱給它們的處理程序,並將數據作為參數傳遞給它們
hub.emit('message', 'hello world'); // 打印 'hello world' 和 'Message event fired'
hub.emit('message', { hello: 'world' }); // 打印 對象 和 'Message event fired'
hub.emit('increment'); // increment = 1

// 停止訂閱
hub.off('message', handler);

6.`memoize`:緩存函數

通過實例化一個Map對象來創建一個空的緩存。

通過檢查輸入值的函數輸出是否已緩存,返回存儲一個參數的函數,該參數將被提供給已記憶的函數;如果沒有,則存儲並返回它。

const memoize = fn => {
const cache = new Map();
const cached = function(val) {
return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);
};
cached.cache = cache;


return cached;
};

Ps: 這個版本可能不是很清晰,還有Vue源碼版的:

/**
* Create a cached version of a pure function.
*/
export function cached (fn: F): F {
const cache = Object.create(null)
return (function cachedFn (str: string) {
const hit = cache[str]
return hit || (cache[str] = fn(str))
}: any)
}

7. `once`:只調用一次的函數

const once = fn => {
let called = false
return function () {
if (!called) {
called = true
fn.apply(this, arguments)
}
}
};

8.`flattenObject`:以鍵的路徑扁平化對象

使用遞歸。

利用Object.keys(obj)聯合Array.prototype.reduce(),以每片葉子節點轉換為扁平的路徑節點。如果鍵的值是一個對象,則函數使用調用適當的自身prefix以創建路徑Object.assign()。否則,它將適當的前綴鍵值對添加到累加器對象。prefix除非您希望每個鍵都有一個前綴,否則應始終省略第二個參數。

const flattenObject = (obj, prefix = '') =>
Object.keys(obj).reduce((acc, k) => {
const pre = prefix.length ? prefix + '.' : '';
if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k));
else acc[pre + k] = obj[k];
return acc;
}, {});

flattenObject({ a: { b: { c: 1 } }, d: 1 }); // { 'a.b.c': 1, d: 1 }

9. `unflattenObject`:以鍵的路徑展開對象

與上面的相反,展開對象。

const unflattenObject = obj =>
Object.keys(obj).reduce((acc, k) => {
if (k.indexOf('.') !== -1) {
const keys = k.split('.');
Object.assign(
acc,
JSON.parse(
'{' +
keys.map((v, i) => (i !== keys.length - 1 ? `"${v}":{` : `"${v}":`)).join('') +
obj[k] +
'}'.repeat(keys.length)
)
);
} else acc[k] = obj[k];
return acc;
}, {});

unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 }

這個的用途,在做Tree組件或複雜表單時取值非常舒服。

3. 第三部分:字符串

1.`byteSize`:返回字符串的字節長度

const byteSize = str => new Blob([str]).size;

byteSize(''); // 4
byteSize('Hello World'); // 11

2. `capitalize`:首字母大寫

const capitalize = ([first, ...rest]) =>
first.toUpperCase() + rest.join('');

capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', true); // 'Foobar'

3. `capitalizeEveryWord`:每個單詞首字母大寫

const capitalizeEveryWord = str => str.replace(/\\b[a-z]/g, char => char.toUpperCase());

capitalizeEveryWord('hello world!'); // 'Hello World!'

4. `decapitalize`:首字母小寫

const decapitalize = ([first, ...rest]) =>
first.toLowerCase() + rest.join('')

decapitalize('FooBar'); // 'fooBar'
decapitalize('FooBar'); // 'fooBar'

5. `luhnCheck`:銀行卡號碼校驗(`luhn`算法)

Luhn算法的實現,用於驗證各種標識號,例如信用卡號,IMEI號,國家提供商標識號等。

與String.prototype.split('')結合使用,以獲取數字數組。獲得最後一個數字。實施luhn算法。如果被整除,則返回,否則返回。

const luhnCheck = num => {
let arr = (num + '')
.split('')
.reverse()
.map(x => parseInt(x));
let lastDigit = arr.splice(0, 1)[0];
let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val * 2) % 9) || 9), 0);
sum += lastDigit;
return sum % 10 === 0;
};

用例:

luhnCheck('4485275742308327'); // true
luhnCheck(6011329933655299); // false
luhnCheck(123456789); // false

補充:銀行卡號碼的校驗規則:

關於luhn算法,可以參考以下文章:

銀行卡號碼校驗算法(Luhn算法,又叫模10算法)

銀行卡號碼的校驗採用Luhn算法,校驗過程大致如下:

從右到左給卡號字符串編號,最右邊第一位是1,最右邊第二位是2,最右邊第三位是3….從右向左遍歷,對每一位字符t執行第三個步驟,並將每一位的計算結果相加得到一個數s。對每一位的計算規則:如果這一位是奇數位,則返回t本身,如果是偶數位,則先將t乘以2得到一個數n,如果n是一位數(小於10),直接返回n,否則將n的個位數和十位數相加返回。如果s能夠整除10,則此號碼有效,否則號碼無效。

因為最終的結果會對10取餘來判斷是否能夠整除10,所以又叫做模10算法。

當然,還是庫比較香: bankcardinfo

6. `splitLines`:將多行字符串拆分為行數組。

使用String.prototype.split()和正則表達式匹配換行符並創建一個數組。

const splitLines = str => str.split(/\\r?\\n/);



splitLines('This\\nis a\\nmultiline\\nstring.\\n'); // ['This', 'is a', 'multiline', 'string.' , '']

7. `stripHTMLTags`:刪除字符串中的`HTMl`標籤

從字符串中刪除HTML / XML標籤。

使用正則表達式從字符串中刪除HTML / XML 標記。

const stripHTMLTags = str => str.replace(/]*>/g, '');

stripHTMLTags('

lorem ipsum

'); // 'lorem ipsum'

4. 第四部分:對象

1. `dayOfYear`:當前日期天數

const dayOfYear = date =>
Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date()); // 285

2. `forOwn`:迭代屬性並執行回調

const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1

3. `Get Time From Date`:返回當前24小時制時間的字符串

const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);

getColonTimeFromDate(new Date()); // "08:38:00"

4. `Get Days Between Dates`:返回日期間的天數

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
(dateFinal - dateInitial) / (1000 * 3600 * 24);

getDaysDiffBetweenDates(new Date('2019-01-01'), new Date('2019-10-14')); // 286

5. `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

6. `isAfterDate`:檢查是否在某日期後

const isAfterDate = (dateA, dateB) => dateA > dateB;

isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true

7. `isBeforeDate`:檢查是否在某日期前

const isBeforeDate = (dateA, dateB) => dateA < dateB;



isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true

8 `tomorrow`:獲取明天的字符串格式時間

const tomorrow = () => {
let t = new Date();
t.setDate(t.getDate() + 1);
return t.toISOString().split('T')[0];
};

tomorrow(); // 2019-10-15 (如果明天是2019-10-15)

9. `equals`:全等判斷

在兩個變量之間進行深度比較以確定它們是否全等。

此代碼段精簡的核心在於Array.prototype.every()的使用。

const equals = (a, b) => {
if (a === b) return true;
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
if (a.prototype !== b.prototype) return false;
let keys = Object.keys(a);
if (keys.length !== Object.keys(b).length) return false;
return keys.every(k => equals(a[k], b[k]));
};

用法:

equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true

5. 第五部分:數字

1. `randomIntegerInRange`:生成指定範圍的隨機整數

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

randomIntegerInRange(0, 5); // 3

2. `randomNumberInRange`:生成指定範圍的隨機小數

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

randomNumberInRange(2, 10); // 6.0211363285087005

3. `round`:四捨五入到指定位數

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

round(1.005, 2); // 1.01

4. `sum`:計算數組或多個數字的總和

const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);

sum(1, 2, 3, 4); // 10
sum(...[1, 2, 3, 4]); // 10

5. `toCurrency`:簡單的貨幣單位轉換

const toCurrency = (n, curr, LanguageFormat = undefined) =>
Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);

toCurrency(123456.789, 'EUR'); // €123,456.79
toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79
toCurrency(123456.789, 'USD', 'fa'); // ۱۲۳٬۴۵۶٫۷۹
toCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423

6. 第六部分:瀏覽器操作及其它

1. `bottomVisible`:檢查頁面底部是否可見

const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);

bottomVisible(); // true

2. `Create Directory`:檢查創建目錄

此代碼段調用fs模塊的existsSync()檢查目錄是否存在,如果不存在,則mkdirSync()創建該目錄。

const fs = require('fs');
const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
createDirIfNotExists('test');

3. `currentURL`:返回當前鏈接`url`

const currentURL = () => window.location.href;

currentURL(); // 'https://juejin.im'

4. `distance`:返回兩點間的距離

該代碼段通過計算歐幾里得距離來返回兩點之間的距離。

const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);


distance(1, 1, 2, 3); // 2.23606797749979

5. `elementContains`:檢查是否包含子元素

此代碼段檢查父元素是否包含子元素。

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

6. `getStyle`:返回指定元素的生效樣式

const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];

getStyle(document.querySelector('p'), 'font-size'); // '16px'

7. `getType`:返回值或變量的類型名

const getType = v =>
v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();

getType(new Set([1, 2, 3])); // 'set'
getType([1, 2, 3]); // 'array'

8. `hasClass`:校驗指定元素的類名

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

9. `hide`:隱藏所有的指定標籤

const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));



hide(document.querySelectorAll('img')); // 隱藏所有標籤

10. `httpsRedirect`:`HTTP` 跳轉 `HTTPS`

const httpsRedirect = () => {
if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
};

httpsRedirect(); // 若在`http://www.baidu.com`, 則跳轉到`https://www.baidu.com`

11.`insertAfter`:在指定元素之後插入新元素

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

//

...

after


insertAfter(document.getElementById('myId'), '

after

');

12.`insertBefore`:在指定元素之前插入新元素

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

insertBefore(document.getElementById('myId'), '

before

'); //

before

...

13. `isBrowser`:檢查是否為瀏覽器環境

此代碼段可用於確定當前運行時環境是否為瀏覽器。這有助於避免在服務器(節點)上運行前端模塊時出錯。

const isBrowser = () => ![typeof window, typeof document].includes('undefined');

isBrowser(); // true (browser)
isBrowser(); // false (Node)

14. ` isBrowserTab`:檢查當前標籤頁是否活動

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

isBrowserTabFocused(); // true

15. `nodeListToArray`:轉換`nodeList`為數組

const nodeListToArray = nodeList => [...nodeList];

nodeListToArray(document.childNodes); // [ , html ]

16. `Random Hexadecimal Color Code`:隨機十六進制顏色

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

randomHexColorCode(); // "#e34155"

17. `scrollToTop`:平滑滾動至頂部

該代碼段可用於平滑滾動到當前頁面的頂部。

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

scrollToTop();

18. `smoothScroll`:滾動到指定元素區域

該代碼段可將指定元素平滑滾動到瀏覽器窗口的可見區域。

const smoothScroll = element =>
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});

smoothScroll('#fooBar');
smoothScroll('.fooBar');

19. `detectDeviceType`:檢測移動/PC設備

const detectDeviceType = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'Mobile'
: 'Desktop';

20. `getScrollPosition`:返回當前的滾動位置

默認參數為window ,pageXOffset(pageYOffset)為第一選擇,沒有則用scrollLeft(scrollTop)

const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});



getScrollPosition(); // {x: 0, y: 200}

21. `size`:獲取不同類型變量的長度

這個的實現非常巧妙,利用Blob類文件對象的特性,獲取對象的長度。

另外,多重三元運算符,是真香。

const size = val =>
Array.isArray(val)
? val.length
: val && typeof val === 'object'
? val.size || val.length || Object.keys(val).length
: typeof val === 'string'
? new Blob([val]).size
: 0;

size([1, 2, 3, 4, 5]); // 5
size('size'); // 4
size({ one: 1, two: 2, three: 3 }); // 3

22. `escapeHTML`:轉義`HTML`

當然是用來防XSS攻擊啦。

const escapeHTML = str =>
str.replace(
/[&<>'"]/g,
tag =>
({
'&': '&',
' '>': '>',
"'": ''',
'"': '"'
}[tag] || tag)
);

escapeHTML(' '); // ' '