该方法用于检测给出的日期是否有效:
const isDateValid=(...val)=> !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00"); // true
复制代码
该方法用于计算两个日期之间的间隔时间:
const dayDif=(date1, date2)=> Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2021-11-3"), new Date("2022-2-1")) // 90
复制代码
距离过年还有90天~
该方法用于检测给出的日期位于今年的第几天:
const dayOfYear=(date)=> Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date()); // 307
复制代码
2021年已经过去300多天了~
该方法可以用于将时间转化为hour:minutes:seconds的格式:
const timeFromDate=date=> date.toTimeString().slice(0, 8);
timeFromDate(new Date(2021, 11, 2, 12, 30, 0)); // 12:30:00
timeFromDate(new Date()); // 返回当前时间 09:00:00
复制代码
该方法用于将英文字符串的首字母大写处理:
const capitalize=str=> str.charAt(0).toUpperCase() + str.slice(1)
capitalize("hello world") // Hello world
复制代码
该方法用于将一个字符串进行翻转操作,返回翻转后的字符串:
const reverse=str=> str.split('').reverse().join('');
reverse('hello world'); // 'dlrow olleh'
复制代码
该方法用于生成一个随机的字符串:
const randomString=()=> Math.random().toString(36).slice(2);
randomString();
复制代码
该方法可以从指定长度处截断字符串:
const truncateString=(string, length)=> string.length < length ? string : `${string.slice(0, length - 3)}...`;
truncateString('Hi, I should be truncated because I am too loooong!', 36) // 'Hi, I should be truncated because...'
复制代码
该方法用于去除字符串中的HTML元素:
const stripHtml=html=> (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
复制代码
该方法用于移除数组中的重复项:
const removeDuplicates=(arr)=> [...new Set(arr)];
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));
复制代码
该方法用于判断一个数组是否为空数组,它将返回一个布尔值:
const isNotEmpty=arr=> Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]); // true
复制代码
可以使用下面两个方法来合并两个数组:
const merge=(a, b)=> a.concat(b);
const merge=(a, b)=> [...a, ...b];
复制代码
该方法用于判断一个数字是奇数还是偶数:
const isEven=num=> num % 2===0;
isEven(996);
复制代码
const average=(...args)=> args.reduce((a, b)=> a + b) / args.length;
average(1, 2, 3, 4, 5); // 3
复制代码
该方法用于获取两个整数之间的随机整数
const random=(min, max)=> Math.floor(Math.random() * (max - min + 1) + min);
random(1, 50);
复制代码
该方法用于将一个数字按照指定位进行四舍五入:
const round=(n, d)=> Number(Math.round(n + "e" + d) + "e-" + d)
round(1.005, 2) //1.01
round(1.555, 2) //1.56
复制代码
该方法可以将一个RGB的颜色值转化为16进制值:
const rgbToHex=(r, g, b)=> "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(255, 255, 255); // '#ffffff'
复制代码
该方法用于获取一个随机的十六进制颜色值:
const randomHex=()=> `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
randomHex();
复制代码
该方法使用 navigator.clipboard.writeText 来实现将文本复制到剪贴板:
const copyToClipboard=(text)=> navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
复制代码
该方法可以通过使用 document.cookie 来访问 cookie 并清除存储在网页中的所有 cookie:
const clearCookies=document.cookie.split(';').forEach(cookie=> document.cookie=cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
复制代码
该方法通过内置的 getSelection 属性获取用户选择的文本:
const getSelectedText=()=> window.getSelection().toString();
getSelectedText();
复制代码
该方法用于检测当前的环境是否是黑暗模式,它是一个布尔值:
const isDarkMode=window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode)
复制代码
该方法用于在页面中返回顶部:
const goToTop=()=> window.scrollTo(0, 0);
goToTop();
复制代码
该方法用于检测当前标签页是否已经激活:
const isTabInView=()=> !document.hidden;
复制代码
该方法用于检测当前的设备是否是苹果的设备:
const isAppleDevice=()=> /Mac|iPod|iPhone|iPad/.test(navigator.platform);
isAppleDevice();
复制代码
该方法用于判断页面是否已经底部:
const scrolledToBottom=()=> document.documentElement.clientHeight + window.scrollY >=document.documentElement.scrollHeight;
复制代码
该方法用于重定向到一个新的URL:
const redirect=url=> location.href=url
redirect("https://www.google.com/")
复制代码
该方法用于打开浏览器的打印框:
const showPrintDialog=()=> window.print()
复制代码
该方法可以返回一个随机的布尔值,使用Math.random()可以获得0-1的随机数,与0.5进行比较,就有一半的概率获得真值或者假值。
const randomBoolean=()=> Math.random() >=0.5;
randomBoolean();
复制代码
可以使用以下形式在不适用第三个变量的情况下,交换两个变量的值:
[foo, bar]=[bar, foo];
复制代码
该方法用于获取一个变量的类型:
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
复制代码
该方法用于摄氏度和华氏度之间的转化:
const celsiusToFahrenheit=(celsius)=> celsius * 9/5 + 32;
const fahrenheitToCelsius=(fahrenheit)=> (fahrenheit - 32) * 5/9;
celsiusToFahrenheit(15); // 59
celsiusToFahrenheit(0); // 32
celsiusToFahrenheit(-20); // -4
fahrenheitToCelsius(59); // 15
fahrenheitToCelsius(32); // 0
复制代码
该方法用于检测一个JavaScript对象是否为空:
const isEmpty=obj=> Reflect.ownKeys(obj).length===0 && obj.constructor===Object;
该方法用于检测给出的日期是否有效:
const isDateValid=(...val)=> !Number.isNaN(new Date(...val).valueOf());
isDateValid("December 17, 1995 03:24:00"); // true
复制代码
该方法用于计算两个日期之间的间隔时间:
const dayDif=(date1, date2)=> Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000)
dayDif(new Date("2021-11-3"), new Date("2022-2-1")) // 90
复制代码
距离过年还有90天~
该方法用于检测给出的日期位于今年的第几天:
const dayOfYear=(date)=> Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);
dayOfYear(new Date()); // 307
复制代码
2021年已经过去300多天了~
该方法可以用于将时间转化为hour:minutes:seconds的格式:
const timeFromDate=date=> date.toTimeString().slice(0, 8);
timeFromDate(new Date(2021, 11, 2, 12, 30, 0)); // 12:30:00
timeFromDate(new Date()); // 返回当前时间 09:00:00
复制代码
该方法用于将英文字符串的首字母大写处理:
const capitalize=str=> str.charAt(0).toUpperCase() + str.slice(1)
capitalize("hello world") // Hello world
复制代码
该方法用于将一个字符串进行翻转操作,返回翻转后的字符串:
const reverse=str=> str.split('').reverse().join('');
reverse('hello world'); // 'dlrow olleh'
复制代码
该方法用于生成一个随机的字符串:
const randomString=()=> Math.random().toString(36).slice(2);
randomString();
复制代码
该方法可以从指定长度处截断字符串:
const truncateString=(string, length)=> string.length < length ? string : `${string.slice(0, length - 3)}...`;
truncateString('Hi, I should be truncated because I am too loooong!', 36) // 'Hi, I should be truncated because...'
复制代码
该方法用于去除字符串中的HTML元素:
const stripHtml=html=> (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
复制代码
该方法用于移除数组中的重复项:
const removeDuplicates=(arr)=> [...new Set(arr)];
console.log(removeDuplicates([1, 2, 2, 3, 3, 4, 4, 5, 5, 6]));
复制代码
该方法用于判断一个数组是否为空数组,它将返回一个布尔值:
const isNotEmpty=arr=> Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]); // true
复制代码
可以使用下面两个方法来合并两个数组:
const merge=(a, b)=> a.concat(b);
const merge=(a, b)=> [...a, ...b];
复制代码
该方法用于判断一个数字是奇数还是偶数:
const isEven=num=> num % 2===0;
isEven(996);
复制代码
const average=(...args)=> args.reduce((a, b)=> a + b) / args.length;
average(1, 2, 3, 4, 5); // 3
复制代码
该方法用于获取两个整数之间的随机整数
const random=(min, max)=> Math.floor(Math.random() * (max - min + 1) + min);
random(1, 50);
复制代码
该方法用于将一个数字按照指定位进行四舍五入:
const round=(n, d)=> Number(Math.round(n + "e" + d) + "e-" + d)
round(1.005, 2) //1.01
round(1.555, 2) //1.56
复制代码
该方法可以将一个RGB的颜色值转化为16进制值:
const rgbToHex=(r, g, b)=> "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(255, 255, 255); // '#ffffff'
复制代码
该方法用于获取一个随机的十六进制颜色值:
const randomHex=()=> `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
randomHex();
复制代码
该方法使用 navigator.clipboard.writeText 来实现将文本复制到剪贴板:
const copyToClipboard=(text)=> navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
复制代码
该方法可以通过使用 document.cookie 来访问 cookie 并清除存储在网页中的所有 cookie:
const clearCookies=document.cookie.split(';').forEach(cookie=> document.cookie=cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
复制代码
该方法通过内置的 getSelection 属性获取用户选择的文本:
const getSelectedText=()=> window.getSelection().toString();
getSelectedText();
复制代码
该方法用于检测当前的环境是否是黑暗模式,它是一个布尔值:
const isDarkMode=window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
console.log(isDarkMode)
复制代码
该方法用于在页面中返回顶部:
const goToTop=()=> window.scrollTo(0, 0);
goToTop();
复制代码
该方法用于检测当前标签页是否已经激活:
const isTabInView=()=> !document.hidden;
复制代码
该方法用于检测当前的设备是否是苹果的设备:
const isAppleDevice=()=> /Mac|iPod|iPhone|iPad/.test(navigator.platform);
isAppleDevice();
复制代码
该方法用于判断页面是否已经底部:
const scrolledToBottom=()=> document.documentElement.clientHeight + window.scrollY >=document.documentElement.scrollHeight;
复制代码
该方法用于重定向到一个新的URL:
const redirect=url=> location.href=url
redirect("https://www.google.com/")
复制代码
该方法用于打开浏览器的打印框:
const showPrintDialog=()=> window.print()
复制代码
该方法可以返回一个随机的布尔值,使用Math.random()可以获得0-1的随机数,与0.5进行比较,就有一半的概率获得真值或者假值。
const randomBoolean=()=> Math.random() >=0.5;
randomBoolean();
复制代码
可以使用以下形式在不适用第三个变量的情况下,交换两个变量的值:
[foo, bar]=[bar, foo];
复制代码
该方法用于获取一个变量的类型:
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
复制代码
该方法用于摄氏度和华氏度之间的转化:
const celsiusToFahrenheit=(celsius)=> celsius * 9/5 + 32;
const fahrenheitToCelsius=(fahrenheit)=> (fahrenheit - 32) * 5/9;
celsiusToFahrenheit(15); // 59
celsiusToFahrenheit(0); // 32
celsiusToFahrenheit(-20); // -4
fahrenheitToCelsius(59); // 15
fahrenheitToCelsius(32); // 0
复制代码
该方法用于检测一个JavaScript对象是否为空:
const isEmpty=obj=> Reflect.ownKeys(obj).length===0 && obj.constructor===Object;
avaScript是一个非常灵活的语言,对于同一个功能往往有多个实现方式。正式因为JavaScript的灵活性,产生了一些一行代码的解决方案。写法简洁,功能完善,美观好看~
下面是我为大家整理的10个一行代码,包括一些常用的场景例如复制到剪切板、回到页面顶部。如果觉得有帮助,欢迎收藏、转发。
这是最常见的需求,实现的方式有很多。可以借助浏览器的API,也有第三方库的实现。
这种需求在中文环境中应该比较少,可以了解一下。
数组去重在开发中经常遇到,在面试中也是常见的题。
利用数组reduce方法不仅可以实现平均值,还可以计算总和、最大值、最小值。
回到顶部是PC和APP长页面常见的功能。
面试常考的题型,实现起来也很简单。
之前写过一篇关于判断奇数偶数的NPM包,用这个一行代码就能实现。
随机打乱数组可能会在一些活动、游戏场景里用到。
数组自身API。
使用解构赋值可以实现两个变量的交换,而且不用借助临时变量。
10个实用的JavaScript一行代码就和大家分享完了,欢迎大家点赞、评论、转发。
*请认真填写需求信息,我们会在24小时内与您取得联系。