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}];
const sumBy = (arr, key) => arr.reduce((acc, obj) => acc + obj[key], 0);
sumBy(arrayOfObjects, 'x'));
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;
const toTimeString = seconds => new Date(seconds * 1000).toISOString().substr(11, 8);
toTimeString(seconds));
9、提取文件扩展名
const fileName = 'example.png'
const getFileExtension = str => str.slice(((str.lastIndexOf(".") - 1) >>> 0) + 2)
// 结果: getFileExtension = 'png'