专栏名称: 开源前线
推荐热门开源软件,播报最新开源项目和开源资讯!
目录
相关文章推荐
中核集团  ·  中核集团召开总部卓越绩效模式贯标动员会 ·  7 小时前  
中核集团  ·  卓越绩效大家谈⑥ ·  昨天  
中核集团  ·  校园招聘🥰 ·  2 天前  
中核集团  ·  校园招聘🤗 ·  3 天前  
51好读  ›  专栏  ›  开源前线

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

开源前线  · 公众号  ·  · 2021-04-21 10:24

正文

开源最前线 今天

开源最前线(ID:OpenSourceTop) 猿妹整编

链接: https://github.com/30-seconds/30-seconds-of-code


今天要和大家分享一个项目,里面精心收集了大量有用的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(next1000); },
  next => { console.log('1 second');  setTimeout(next1000); },
  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}






请到「今天看啥」查看全文