5 个可添加到实用程序库的 JavaScript 函数
我们每个人都有自己的实用程序——处理日期/时间、验证常见表单等等,或者你可能使用第三方实用程序库,例如 lodash 或 underscore。无论如何,下面是一些实用的 JavaScript 函数集合,你可以使用它们来创建或扩展你的实用程序库!尽情享受吧,并在评论区留下你自己的实用程序函数。
1. 使用省略号总结文本
/**
* Accepts a string value and returns it back with an ellipsis if the string length
* is greater than the max length specified. Otherwise, return the original string.
*/
function summarize(str, max) {
return str.length > max ? str.substring(0, max) + '...' : str;
}
2. 在 DOM 对象集合上添加/删除类
使用原型扩展 NodeList。它允许我们使用类似 jQuery 的功能,向使用 querySelectorAll() 在 DOM 上选择的多个对象添加或删除类。
免责声明:一般来说,不建议扩展核心 JS API,但在某些孤立的用例中可能会有用且方便。
NodeList.prototype.addClass = function(className) {
this.forEach(el => {
el.classList.add(className);
});
};
NodeList.prototype.removeClass = function(className) {
this.forEach(el => {
el.classList.remove(className);
});
};
然后你可以像这样使用它们:
// our way
document.querySelectorAll('.menu-item').addClass('disabled');
document.querySelectorAll('.menu-item').removeClass('disabled');
// standard way
const menuItems = document.querySelectorAll('.menu-item');
menuItems.forEach(el => {
el.addClass('disabled');
});
// jQuery way
$('.menu-item').addClass('disabled');
$('.menu-item').removeClass('disabled');
3. 功能性能测试器
使用 console.time() 测试函数的性能。只要使用 async/await,它也适用于异步函数。
// outputs elapsed execution time of your method to your web console
function perfTest(name, method) {
console.time(`Method - ${name}`);
method.apply();
console.timeEnd(`Method - ${name}`);
}
// usage
// function to test
function square() {
for (let i = 0; i < 100000; i++) {
let square = i ** 2;
}
}
// test it
perfTest('square', square); // output -> Method - square: 3.966064453125ms
4. 动态 div 生成器
如果你喜欢动态创建 DOM 元素,这个方法可能会对你有用。它是一种通过将属性作为对象传递来创建 div 元素的方法。
// creates a div, sets provided attributes, returns the div for doing whatever you want with it
function divMe(attr) {
const div = document.createElement('div');
for (let i in attr) {
div.setAttribute(i, attr[i]);
}
return div;
}
// usage
const div = divMe({
class : 'blue-button',
'data-id' : 'abc123',
'aria-label' : 'Close'
});
document.getElementById('container').appendChild(div);
}
5.按键分组数组
返回一个按您定义的键分组的新数组。其工作原理类似于 SQL 中的 GROUP BY 操作。
function groupBy(arr, key) {
return arr.reduce((acc, i) => {
(acc[i[key]] = acc[i[key]] || []).push(i);
return acc;
}, {});
}
// raw data example
const roleModels = [
{
userId: 1,
name: 'John Williams',
type: 'Composer'
},
{
userId: 2,
name: 'Hans Zimmer',
type: 'Composer'
},
{
userId: 3,
name: 'Michael Jordan',
type: 'Athlete'
},
{
userId: 4,
name: 'J.K. Rowling',
type: 'Author'
}
];
const byType = groupBy(roleModels, 'type');
// results (derived):
{
Athlete: [{...}],
Author: [{...}],
Composer: [
{
userId: 1,
name: 'John Williams',
type: 'Composer'
},
{
userId: 2,
name: 'Hans Zimmer',
type: 'Composer'
}
]
}
实用程序是复用上述各种函数的绝佳方式。如果您愿意,甚至可以将它们组织成模块。这取决于您!您经常使用哪些实用程序函数?请在下方评论区分享!
文章来源:https://dev.to/eaich/5-javascript-functions-to-add-to-your-utilities-library-l6j