去重
利用数组的 filter、findIndex 方法实现去重
const arr = [1,1,2,2,3,3,4,4,5,5]
const newArr = arr.filter((item, index) => index === arr.findIndex(item2 => item2 === item))
console.log(newArr);
检测是否为空对象
Reflect.ownKeys 返回一个对象的所有key所组成的数组。通过判断其长度来判断是否为空对象。
/**
*
* @param {Object} obj
*/
function isEmptyObject(obj) {
return Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
}
console.log(isEmptyObject({a: 1}));
检测当前选项卡是否在后台
在浏览器中浏览其它选项卡了。
const isTabActive = () => !document.hidden;
isTabActive()
// true|false
判断是移动端还是 PC 端
const judgeDeviceType =
() => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC';
judgeDeviceType() // PC | Mobile
文字复制进剪切板
const copyText = async (text) => await navigator.clipboard.writeText(text)
copyText('单行代码 前端世界')
获取选中的文字
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
// 返回选中的内容
判断是否是周末
getDay 方法返回一周的第几天,返回0 ~ 6。只有0 和 6 被 6 取余都为0。
const isWeekend = (date) => date.getDay() % 6 === 0;
console.log('今天是否是周末:', isWeekend(new Date(2022, 12, 7)));
// true
求数组平均值
const average = (arr) => arr.reduce((a, b) => a + b) / arr.length;
// 16
console.log(average([1,9,18,36]));
求数组最大值,最小值
利用数组的 reduce 方法。
const arr = [1,2,3,4,5,23,35,234,123243]
const max = arr.reduce((x,y) => x > y ? x : y)
const min = arr.reduce((x,y) => x > y ? y : x)
console.log(max, min, 'max, min');
数组中过滤掉加值
利用 Boolean
const arr = [12,'1223','',null,undefined,'123',1232435]
const filter = arr.filter(Boolean)
console.log(filter,'filter');