常用方法

51 阅读1分钟

1、将 NodeList 转换为数组

const nodesArray = [ ...document.querySelectorAll('div') ];

2、将文本复制到剪贴板

navigator.clipboard.writeText('Text to copy');

3、删除数组重复项

const arr = [1, 2, 2, 3, 4, 4, 5]; const unique = [...new Set(arr)];

4、离线状态检查器

const isOnline = navigator.onLine ? '在线' : '离线'; 
// 结果: isOnline = '在线''离线'

5、离开页面弹出确对话框

window.onbeforeunload = ()=>'你确定要离开吗?'

6、对象数组,根据对象的某个key求对应值的总和

const arrayOfObjects = [{x: 1}, {x: 2}, {x: 3}]; 
// 指定要求和的 key值 
const sumBy = (arr, key) => arr.reduce((acc, obj) => acc + obj[key], 0); 
// 传入 'x',求元素对象 key 为 'x' 的值的总和 
sumBy(arrayOfObjects, 'x')); 
// 结果: 6

7、将 url 问号后面的查询字符串转为对象

const query = 'name=John&age=30';
// 将字符串解析为对象 
const parseQuery = query => Object.fromEntries(new URLSearchParams(query));
// 结果: parseQuery = { name: 'John', age: '30' }

8、将秒数转换为时间格式的字符串

const seconds = 3661; 
// 一小时是 3600 秒,多出 61 秒 
const toTimeString = seconds => new Date(seconds * 1000).toISOString().substr(11, 8);
toTimeString(seconds));
// 结果: '01:01:01'

9、提取文件扩展名

const fileName = 'example.png';
const getFileExtension = str => str.slice(((str.lastIndexOf(".") - 1) >>> 0) + 2);
// 结果: getFileExtension = 'png'