這個(gè)開源項(xiàng)目絕了!30秒就能理解的JavaScript優(yōu)秀代碼
今天要和大家分享一個(gè)項(xiàng)目,里面精心收集了大量有用的JavaScript代碼片段,讓你能夠在極短的時(shí)間內(nèi)可以理解使用它們,分為日期、節(jié)點(diǎn)、功能模塊等部分,你可以直接將文件的這些代碼直接導(dǎo)入到你的的文本編輯器(VSCode,Atom,Sublime)。
這個(gè)項(xiàng)目在Github上十分受歡迎,目前標(biāo)星 71.3K,累計(jì)分支 7.9K(Github地址:https://github.com/30-seconds/30-seconds-of-code)
下面還是一起來看看這個(gè)項(xiàng)目里都有哪些代碼段吧:
數(shù)組:arrayMax
返回?cái)?shù)組中的最大值。將Math.max()與擴(kuò)展運(yùn)算符 (...) 結(jié)合使用以獲取數(shù)組中的最大值。
- const arrayMin = arr => Math.min(...arr);
- // arrayMin([10, 1, 5]) -> 1
瀏覽器:bottomVisible
如果頁的底部可見, 則返回true, 否則為false。使用scrollY、scrollHeight和clientHeight來確定頁面底部是否可見。
- const bottomVisible = () =>
- document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
- // bottomVisible() -> true
日期:getDaysDiffBetweenDates
返回兩個(gè)日期之間的差異 (以天為值)。計(jì)算Date對象之間的差異 (以天為值)。
- const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);
- // getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) -> 9
函數(shù):chainAsync
鏈異步函數(shù),循環(huán)遍歷包含異步事件的函數(shù)數(shù)組, 當(dāng)每個(gè)異步事件完成時(shí)調(diào)用next。
- const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); };
- /*
- chainAsync([
- next => { console.log('0 seconds'); setTimeout(next, 1000); },
- next => { console.log('1 second'); setTimeout(next, 1000); },
- next => { console.log('2 seconds'); }
- ])
- */
數(shù)學(xué):arrayAverage
返回?cái)?shù)字?jǐn)?shù)組的平均值。使用Array.reduce()將每個(gè)值添加到累加器中, 并以0的值初始化, 除以數(shù)組的length。
- const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
- // arrayAverage([1,2,3]) -> 2
節(jié)點(diǎn):JSONToFile
將 JSON 對象寫入文件。使用fs.writeFile()、模板文本和JSON.stringify()將json對象寫入.json文件。
- const fs = require('fs');
- const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2))
- // JSONToFile({test: "is passed"}, 'testJsonFile') -> writes the object to 'testJsonFile.json'
對象:cleanObj
移除從 JSON 對象指定的屬性之外的任何特性。使用Object.keys()方法可以遍歷給定的 json 對象并刪除在給定數(shù)組中不是included 的鍵。另外, 如果給它一個(gè)特殊的鍵 (childIndicator), 它將在里面深入搜索, 并將函數(shù)應(yīng)用于內(nèi)部對象。
- const cleanObj = (obj, keysToKeep = [], childIndicator) => {
- Object.keys(obj).forEach(key => {
- if (key === childIndicator) {
- cleanObj(obj[key], keysToKeep, childIndicator);
- } else if (!keysToKeep.includes(key)) {
- delete obj[key];
- }
- })
- }
- /*
- const testObj = {a: 1, b: 2, children: {a: 1, b: 2}}
- cleanObj(testObj, ["a"],"children")
- console.log(testObj)// { a: 1, children : { a: 1}}
以上舉的這些示例還只是冰山一角,如果你對這個(gè)項(xiàng)目感興趣就趕緊馬克起來。