這個開源項目絕了!30秒就能理解的JavaScript優秀代碼
今天要和大家分享一個項目,里面精心收集了大量有用的JavaScript代碼片段,讓你能夠在極短的時間內可以理解使用它們,分為日期、節點、功能模塊等部分,你可以直接將文件的這些代碼直接導入到你的的文本編輯器(VSCode,Atom,Sublime)。
這個項目在Github上十分受歡迎,目前標星 71.3K,累計分支 7.9K(Github地址:https://github.com/30-seconds/30-seconds-of-code)
下面還是一起來看看這個項目里都有哪些代碼段吧:
數組:arrayMax
返回數組中的最大值。將Math.max()與擴展運算符 (...) 結合使用以獲取數組中的最大值。
- 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
返回兩個日期之間的差異 (以天為值)。計算Date對象之間的差異 (以天為值)。
- const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);
- // getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) -> 9
函數:chainAsync
鏈異步函數,循環遍歷包含異步事件的函數數組, 當每個異步事件完成時調用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'); }
- ])
- */
數學:arrayAverage
返回數字數組的平均值。使用Array.reduce()將每個值添加到累加器中, 并以0的值初始化, 除以數組的length。
- const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
- // arrayAverage([1,2,3]) -> 2
節點: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 對象并刪除在給定數組中不是included 的鍵。另外, 如果給它一個特殊的鍵 (childIndicator), 它將在里面深入搜索, 并將函數應用于內部對象。
- 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}}
以上舉的這些示例還只是冰山一角,如果你對這個項目感興趣就趕緊馬克起來。