Skip to content

一看就会,自用 js 方法技巧

去重

利用数组的 filter、findIndex 方法实现去重

js
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 所组成的数组。通过判断其长度来判断是否为空对象。

js
/**
 * 
 * @param {Object} obj 
 */
function isEmptyObject(obj) {
	return Reflect.ownKeys(obj).length === 0 && obj.constructor === Object
}

console.log(isEmptyObject({a: 1}));

检测当前选项卡是否在后台

在浏览器中浏览其它选项卡了。

js
const isTabActive = () => !document.hidden; 

isTabActive()
// true|false

判断是移动端还是 PC 端

js
const judgeDeviceType =
      () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC';

judgeDeviceType()  // PC | Mobile

文字复制进剪切板

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard

因为安全问题,这种方法需要用户授权才能成功。

js
const copyText = async (text) => await navigator.clipboard.writeText(text)
copyText('单行代码 前端世界')

获取选中的文字

js
const getSelectedText = () => window.getSelection().toString();

getSelectedText();
// 返回选中的内容

判断是否是周末

getDay 方法返回一周的第几天,返回 0 ~ 6。只有 0 和 6 被 6 取余都为 0。

js
const isWeekend = (date) => date.getDay() % 6 === 0;

console.log('今天是否是周末:', isWeekend(new Date(2022, 12, 7)));
// true

求数组平均值

js
const average = (arr) => arr.reduce((a, b) => a + b) / arr.length;

// 16
console.log(average([1,9,18,36]));

求数组最大值,最小值

利用数组的 reduce 方法。

js
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:

js
const arr = [12,'1223','',null,undefined,'123',1232435]

const filter = arr.filter(Boolean)

console.log(filter,'filter');

Released under the MIT License.