编程 38个实用的JavaScript技巧

2024-11-19 07:42:44 +0800 CST views 599

38个实用的JavaScript技巧

今天这篇文章,我想跟大家分享一些我在日常工作中收集整理的有用JavaScript技巧,希望这些技巧能够帮助你提升开发效率。

01、重新加载当前页面

const reload = () => location.reload();
reload();

02、滚动到页面顶部

const goToTop = () => window.scrollTo(0, 0);
goToTop();

03、元素滚动

将元素平滑地滚动到视口起点:

const scrollToTop = (element) => element.scrollIntoView({ behavior: "smooth", block: "start" });
scrollToTop(document.body);

将元素平滑地滚动到视口端点:

const scrollToBottom = (element) => element.scrollIntoView({ behavior: "smooth", block: "end" });
scrollToBottom(document.body);

04、检查当前浏览器是否为Internet Explorer

const isIE = !!document.documentMode;

05、从给定文本中去除HTML

const stripHtml = (html) => new DOMParser().parseFromString(html, 'text/html').body.textContent || '';
stripHtml('<div>test</div>'); // 'test'

06、重定向

const goTo = (url) => (location.href = url);

07、复制文本到剪贴板

const copy = (text) => navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
copy('你需要粘贴的文本');

08、异步函数检查

const isAsyncFunction = (v) => Object.prototype.toString.call(v) === '[object AsyncFunction]';
isAsyncFunction(async function () {}); // true

09、截断数字

const toFixed = (n, fixed) => `${n}`.match(new RegExp(`^-?\\d+(?:.\\d{0,${fixed}})?`))[0];
toFixed(10.255, 2); // 10.25

10、四舍五入到最接近的数字

const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
round(10.255, 2); // 10.26

11、零填充

const replenishZero = (num, len, zero = 0) => num.toString().padStart(len, zero);
replenishZero(8, 2); // 08

12、删除无效属性

const removeNullUndefined = (obj) => Object.entries(obj).reduce((a, [k, v]) => (v == null ? a : ((a[k] = v), a)), {});
removeNullUndefined({name: '', age: undefined, sex: null}); // { name: '' }

13、反转对象键值对

const invert = (obj) => Object.keys(obj).reduce((res, k) => Object.assign(res, { [obj[k]]: k }), {});
invert({name: 'jack'}); // {jack: 'name'}

14、将字符串转换为对象

const strParse = (str) => JSON.parse(str.replace(/(\w+)\s*:/g, (_, p1) => `"${p1}":`).replace(/'/g, '"'));
strParse('{name: "jack"}');

日期处理技巧

15、检查日期是否为今天

const isToday = (date) => date.toISOString().slice(0, 10) === new Date().toISOString().slice(0, 10);

16、日期转换

const formatYmd = (date) => date.toISOString().slice(0, 10);
formatYmd(new Date());

17、秒转换为 hh:mm:ss 格式

const formatSeconds = (s) => new Date(s * 1000).toISOString().substr(11, 8);
formatSeconds(200); // 00:03:20

18、获取某年某月的第一天

const getFirstDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth(), 1);
getFirstDate(new Date('2024/05'));

19、获取某年某月的最后一天

const getLastDate = (d = new Date()) => new Date(d.getFullYear(), d.getMonth() + 1, 0);
getLastDate(new Date('2023/03/04'));

20、获取给定年份的特定月份的总天数

const getDaysNum = (year, month) => new Date(year, month, 0).getDate;
const day = getDaysNum(2024, 2); // 29

数组处理技巧

21、生成数组

const createArr = (n) => Array.from(new Array(n), (v, i) => i);
createArr(100);

22、随机排列数组

const randomSort = (list) => list.sort(() => Math.random() - 0.5);
randomSort([0,1,2,3,4,5,6,7,8,9]); // 随机排列结果

23、数组去重

const removeDuplicates = (list) => [...new Set(list)];
removeDuplicates([0, 0, 2, 4, 5]); // [0,2,4,5]

24、根据唯一值去重

const duplicateById = (list) => [...list.reduce((prev, cur) => prev.set(cur.id, cur), new Map()).values()];
duplicateById([{id: 1, name: 'jack'}, {id: 2, name: 'rose'}, {id: 1, name: 'jack'}]);

25、多个数组的交集

const intersection = (a, ...arr) => [...new Set(a)].filter((v) => arr.every((b) => b.includes(v)));
intersection([1, 2, 3, 4], [2, 3, 4, 7, 8], [1, 3, 4, 9]); // [3, 4]

26、查找数组中最大值的索引

const indexOfMax = (arr) => arr.reduce((prev, curr, i, a) => (curr > a[prev] ? i : prev), 0);
indexOfMax([1, 3, 9, 7, 5]); // 2

27、查找最小值索引

const indexOfMin = (arr) => arr.reduce((prev, curr, i, a) => (curr < a[prev] ? i : prev), 0);
indexOfMin([2, 5, 3, 4, 1, 0, 9]); // 5

28、查找最接近的数值

const closest = (arr, n) => arr.reduce((prev, curr) => (Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev));
closest([29, 87, 8, 78, 97, 20, 75, 33, 24, 17], 50); // 33

29、压缩多个数组

const zip = (...arr) => Array.from({ length: Math.max(...arr.map((a) => a.length)) }, (_, i) => arr.map((a) => a[i]));
zip([1,2,3,4], ['a', 'b', 'c', 'd'], ['A', 'B', 'C', 'D']);

30、矩阵行列交换

const transpose = (matrix) => matrix[0].map((col, i) => matrix.map((row) => row[i]));
transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]]);

数字转换

31、基数转换

const toDecimal = (num, n = 10) => num.toString(n);
toDecimal(10, 2); // '1010'
const toDecimalism = (num, n = 10) => parseInt(num, n);
toDecimalism(1010, 2); // 10

其他技巧

32、比较两个对象

const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0]));
isEqual({name: 'jack'}, {name: 'jack'}); // true

33、随机颜色生成

const getRandomColor = () => `#${Math.floor(Math.random() * 0

xffffff).toString(16)}`;
getRandomColor(); // '#4c2fd7'

34、颜色格式转换

const hexToRgb = (hex) => hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i, (_, r, g, b) => `#${r}${r}${g}${g}${b}${b}`).substring(1).match(/.{2}/g).map((x) => parseInt(x, 16));
hexToRgb('#00ffff'); // [0, 255, 255]

35、生成随机IP地址

const randomIp = () => Array(4).fill(0).map((_, i) => Math.floor(Math.random() * 255) + (i === 0 ? 1 : 0)).join('.');

36、生成UUID

const uuid = (a) => (a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, uuid));
uuid();

37、获取Cookie

const getCookie = () => document.cookie.split(';').map((item) => item.split('=')).reduce((acc, [k, v]) => (acc[k.trim().replace('"', '')] = v) && acc, {});
getCookie();

38、强制等待

const sleep = async (t) => new Promise((resolve) => setTimeout(resolve, t));
sleep(2000).then(() => { console.log('time') });

总结

以上就是我今天跟你分享的38个实用的JavaScript技巧,记得收藏以备不时之需。感谢阅读,祝开发愉快!

复制全文 生成海报 编程 Web开发 技术分享 JavaScript

推荐文章

赚点点任务系统
2024-11-19 02:17:29 +0800 CST
使用 node-ssh 实现自动化部署
2024-11-18 20:06:21 +0800 CST
Shell 里给变量赋值为多行文本
2024-11-18 20:25:45 +0800 CST
Nginx 性能优化有这篇就够了!
2024-11-19 01:57:41 +0800 CST
php机器学习神经网络库
2024-11-19 09:03:47 +0800 CST
为什么要放弃UUID作为MySQL主键?
2024-11-18 23:33:07 +0800 CST
PHP 唯一卡号生成
2024-11-18 21:24:12 +0800 CST
Vue3中如何进行性能优化?
2024-11-17 22:52:59 +0800 CST
mendeley2 一个Python管理文献的库
2024-11-19 02:56:20 +0800 CST
什么是Vue实例(Vue Instance)?
2024-11-19 06:04:20 +0800 CST
用 Rust 构建一个 WebSocket 服务器
2024-11-19 10:08:22 +0800 CST
MySQL设置和开启慢查询
2024-11-19 03:09:43 +0800 CST
Vue3中的Slots有哪些变化?
2024-11-18 16:34:49 +0800 CST
介绍25个常用的正则表达式
2024-11-18 12:43:00 +0800 CST
程序员茄子在线接单