开源最前线
今天
开源最前线(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
)
返回数组中的最大值。将Math.max()与扩展运算符 (...) 结合使用以获取数组中的最大值。
const arrayMin = arr => Math.min(...arr);
// arrayMin([10, 1, 5]) -> 1
如果页的底部可见, 则返回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
链异步函数,循环遍历包含异步事件的函数数组, 当每个异步事件完成时调用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'); }
])
*/
返回数字数组的平均值。使用Array.reduce()将每个值添加到累加器中, 并以0的值初始化, 除以数组的length。
const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
// arrayAverage([1,2,3]) -> 2
将 JSON 对象写入文件。使用fs.writeFile()、模板文本和JSON.stringify()将json对象写入.json文件。
const fs = require('fs');
const JSONToFile = (obj, filename) => fs.writeFile(`${filename}