1、从对象中删除所有 null 和 undefined 的属性
const removeNullUndefined = (obj) =>
Object.entries(obj)
.reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {});
// 或
const removeNullUndefined = (obj) =>
Object.fromEntries(Object.entries(obj).filter(([_, v]) => v != null));
// 例子
removeNullUndefined({
foo: null,
bar: undefined,
fuzz: 1}
);
// { fuzz: 1 }
2、反转对象的键和值
const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {});
// 或
const invert = (obj) => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));
// 事例
invert({ a: '1', b: '2', c: '3' }); // { 1: 'a', 2: 'b', 3: 'c' }
3、从对象数组中提取指定属性的值
const pluck = (objs, property) => objs.map((obj) => obj[property]);
// Example
const mobile = pluck([
{ name: '小米', price: 3000 },
{ name: '华为', price: 6000 },
{ name: '苹果', price: 5000 },
],
'name');
// [ '小米', '华为', '苹果' ]
4、检查多个对象是否相等
const isEqual = (...objects) => objects.every((obj) =>
JSON.stringify(obj) === JSON.stringify(objects[0]));
// 事例
console.log(isEqual({ foo: 'bar' }, { foo: 'bar' })); // true
console.log(isEqual({ foo: 'bar' }, { bar: 'foo' })); // false
5、根据对象的属性对其进行排序
Object.keys(obj)
.sort()
.reduce((p, c) => ((p[c] = obj[c]), p), {});
// 事例
const colors = {
white: '#ffffff',
black: '#000000',
red: '#ff0000',
green: '#008000',
blue: '#0000ff',
};
sort(colors);
/*
{
black: '#000000',
blue: '#0000ff',
green: '#008000',
red: '#ff0000',
white: '#ffffff',
}
*/
6、大写字符串第一个字符
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalize('hello world'));// Hello world
7、计算两个日期之间的不同天数
const diffDays = (date, otherDate) => Math.ceil(Math.abs(date - otherDate) / 86400000);
// 例子
diffDays(new Date('2021-05-10'), new Date('2021-11-25')); // 199
8、检查日期是否有效
const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00"); // true
9、将URL参数转换为对象
const getUrlParams = (query) =>Array.from(new URLSearchParams(query)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),{});
// 例子
getUrlParams(location.search);
getUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" }
// Duplicate key
getUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" }
10、拷贝到剪切板
const copyToClipboard = (text) =>
navigator.clipboard.writeText(text);
// 例子
copyToClipboard("Hello World");
11、比较两个数组
// `a` 和 `b` 都是数组
const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
// 或者
const isEqual = (a, b) => a.length === b.length &&
a.every((v, i) => v === b[i]);
// 事例
isEqual([1, 2, 3], [1, 2, 3]); // true
isEqual([1, 2, 3], [1, '2', 3]); // false
12、获取选中文本
const getSelectedText = () => window.getSelection().toString();
13、滚动到页面顶部
const scrollToTop = () => window.scrollTo(0, 0);
scrollToTop()
14、清除空格
String.prototype.trim = function() {
var reExtraSpace = /^\s*(.*?)\s+$/;
return this.replace(reExtraSpace, "$1")
}
15、日期格式化
Date.prototype.format = function(format){
var o = {
"M+" : this.getMonth()+1, //month
"d+" : this.getDate(), //day
"h+" : this.getHours(), //hour
"m+" : this.getMinutes(), //minute
"s+" : this.getSeconds(), //second
"q+" : Math.floor((this.getMonth()+3)/3), //quarter
"S" : this.getMilliseconds() //millisecond
};
if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
(this.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o){
if(new RegExp("("+ k +")").test(format))
format = format.replace(RegExp.$1,RegExp.$1.length==1 ? o[k] :("00"+ o[k]).substr((""+ o[k]).length));
}
return format;
}
new Date().format("yyyy-MM-dd")
日常开发中有好多很好的实用方法,多多积累,让我们快乐的摸鱼~