当前位置:首页 > IT科技

这个开源项目绝了!30秒就能理解的JavaScript优秀代码

今天要和大家分享一个项目,个开里面精心收集了大量有用的源项t优JavaScript代码片段,让你能够在极短的目绝秒能码时间内可以理解使用它们,分为日期、理解节点、秀代功能模块等部分,个开你可以直接将文件的源项t优这些代码直接导入到你的的文本编辑器(VSCode,Atom,目绝秒能码Sublime)。理解

这个项目在Github上十分受欢迎,秀代目前标星 71.3K,个开累计分支 7.9K(Github地址:https://github.com/30-seconds/30-seconds-of-code)

下面还是源项t优一起来看看这个项目里都有哪些代码段吧:

数组: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}} 

以上举的这些示例还只是冰山一角,如果你对这个项目感兴趣就赶紧马克起来。

源码下载

分享到:

滇ICP备2023006006号-16