29 个有用的 JavaScript 单行代码

今天这篇文章,我主要是想跟大家分享一些关于JavaScript的单行代码技巧,在这些方法中,我们使用了一些API,帮助我们简化操作,可能有些方法写一行不是很优雅,我们这么做的目的,主要是为了进一步学习使用API的技巧,希望对你的学习有所帮助。

现在,我们就开始进入今天的内容。

1.复制内容到剪贴板

const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");

2.清除所有cookie

const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));

3.获取选中的文字​​​​​​

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

4.滚动到页面顶部​​​​​​

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

5.判断当前tab是否激活

const isTabInView = () => !document.hidden;

6.判断当前设备是否为苹果设备

const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);
isAppleDevice();

7.是否滚动到页面底部

const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;

8. 重定向到一个 URL

const redirect = url => location.href = url
redirect("https://www.google.com/")

9.打开浏览器打印框

const showPrintDialog = () => window.print()

10.随机布尔​​​​​​

const randomBoolean = () => Math.random() >= 0.5;
randomBoolean();

11.变量交换

[foo, bar] = [bar, foo];

12.获取变量的类型​​​​​​​

const trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
trueTypeOf('');     // string
trueTypeOf(0);      // number
trueTypeOf();       // undefined
trueTypeOf(null);   // null
trueTypeOf({});     // object
trueTypeOf([]);     // array
trueTypeOf(0);      // number
trueTypeOf(() => {});  // function

13.检查对象是否为空

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;

14.检查日期是否有效​​​​​​​

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 2022 03:24:00");

15.计算两个日期之间的间隔​​​​​​​

const dayDif = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
    
dayDif(new Date("2022-11-3"), new Date("2023-2-1"));

16. 找出日期所在年份中的第几天​​​​​​​

const dayOfYear = (date) => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date());

17.时间格式化​​​​​​​

const timeFromDate = date => date.toTimeString().slice(0, 8);
    
timeFromDate(new Date(2022, 11, 2, 12, 30, 0));
timeFromDate(new Date());

18.将字符串首字母大写​​​​​​​

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)
capitalize("hello world")

19.翻转字符串​​​​​​​

const reverse = str => str.split('').reverse().join('');reverse('hello world');

20.随机字符串

const randomString = () => Math.random().toString(36).slice(2);
randomString();

​​​​​​21. 截断字符串​​​​​​​

const truncateString = (string, length) => string.length < length ? string : `${string.slice(0, length - 3)}...`;
truncateString('Hi, I am too loooong!', 12);

22. 从字符串中删除 HTML

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

23. 删除数组中的重复项​​​​​​​

const removeDuplicates = (arr) => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));

24.检查数组是否为空

const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);

​​​​​​​25.合并两个数组

const merge = (a, b) => a.concat(b);
const merge = (a, b) => [...a, ...b];

​​​​​26.判断一个数是奇数还是偶数​​​​​​

const isEven = num => num % 2 === 0;
isEven(1024);

27. 求一组数的平均值​​​​​​​

const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4, 5);

28. 获取两个整数之间的随机整数​​​​​​​

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
random(1, 50);

29.四舍五入到指定位数​​​​​​​

const round = (n, d) => Number(Math.round(n + "e" + d) + "e-" + d)
round(1.005, 2);
round(1.555, 2);

你可能感兴趣的:(前端,javascript,前端,开发语言)