今天想和大家分享一个项目,精心收集了大量有用的JavaScript代码片段,让你在极短的时间内理解并使用它们,分为dates,nodes,functionmodules等部分,你可以直接将文件的这些代码导入你的文本编辑器(VSCode,Atom,Sublime)。这个项目在Github上很火,目前打了71.3K星,累计分支7.9K(Github地址:https://github.com/30-seconds/30-seconds-of-code)一起来看看在这一起项目中有哪些代码段:array:arrayMax返回数组中的最大值。将Math.max()与扩展运算符(...)结合使用可获取数组中的最大值。constarrayMin=arr=>Math.min(...arr);//arrayMin([10,1,5])->1browser:bottomVisible如果页面底部可见则返回true,否则返回false。使用scrollY、scrollHeight和clientHeight来确定页面底部是否可见。constbottomVisible=()=>document.documentElement.clientHeight+window.scrollY>=document.documentElement.scrollHeight||document.documentElement.clientHeight;//bottomVisible()->truedate:getDaysDiffBetweenDates返回两个日期之间的差异(以天为单位)).计算Date对象之间的差异(以天为单位)。constgetDaysDiffBetweenDates=(dateInitial,dateFinal)=>(dateFinal-dateInitial)/(1000*3600*24);//getDaysDiffBetweenDates(newDate("2017-12-13"),newDate("2017-12-22"))->9function:chainAsync链接异步函数,循环遍历包含异步事件的函数数组,并在每个异步事件完成时调用next。constchainAsync=fns=>{letcurr=0;constnext=()=>fns[curr++](next);next();};/*chainAsync([next=>{console.log('0seconds');setTimeout(next,1000);},next=>{console.log('1second');setTimeout(next,1000);},next=>{console.log('2seconds');}])*/math:arrayAverage返回数字数组的平均值。使用Array.reduce()将每个值添加到累加器,用值0初始化,除以数组的长度。constarrayAverage=arr=>arr.reduce((acc,val)=>acc+val,0)/arr.length;//arrayAverage([1,2,3])->2个节点:JSONToFile写入JSON对象文档。使用fs.writeFile()、模板文字和JSON.stringify()将json对象写入.json文件。constfs=require('fs');constJSONToFile=(obj,filename)=>fs.writeFile(`${filename}.json`,JSON.stringify(obj,null,2))//JSONToFile({test:"ispassed"},'testJsonFile')->writetheobjectto'testJsonFile.json'object:cleanObj删除JSON对象指定的属性以外的任何属性。使用Object.keys()方法遍历给定的json对象并删除不包含在给定数组中的键。另外,如果你给它一个特殊的键(childIndicator),它会深入内部搜索并将函数应用于内部对象。constcleanObj=(obj,keysToKeep=[],childIndicator)=>{Object.keys(obj).forEach(key=>{if(key===childIndicator){cleanObj(obj[key],keysToKeep,childIndicator);}elseif(!keysToKeep.includes(key)){deleteobj[key];}})}/*consttestObj={a:1,b:2,children:{a:1,b:2}}cleanObj(testObj,["a"],"children")console.log(testObj)//{a:1,children:{a:1}}以上例子只是冰山一角,如果你对这个项目感兴趣,赶快行动吧马克站起来。
