今天要和大家分享一个项目,里面精心收集了大量有用的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
- 1.
- 2.
浏览器:bottomVisible
如果页的底部可见, 则返回true, 否则为false。使用scrollY、scrollHeight和clientHeight来确定页面底部是否可见。
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight;
// bottomVisible() -> true
- 1.
- 2.
- 3.
日期:getDaysDiffBetweenDates
返回两个日期之间的差异 (以天为值)。计算Date对象之间的差异 (以天为值)。
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24);
// getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) -> 9
- 1.
- 2.
函数: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'); }
])
*/
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
数学:arrayAverage
返回数字数组的平均值。使用Array.reduce()将每个值添加到累加器中, 并以0的值初始化, 除以数组的length。
const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;
// arrayAverage([1,2,3]) -> 2
- 1.
- 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'
- 1.
- 2.
- 3.
对象: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}}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
以上举的这些示例还只是冰山一角,如果你对这个项目感兴趣就赶紧马克起来。