JS技巧
JS单行代码技巧
1 获取浏览器的Cookie值
通过使用document.cookie
访问来检索cookie的值
const cookie = name => ` ; ${ document. cookie} ` . split ( ` ; ${ name} = ` ) . pop ( ) . split ( ';' ) . shift ( ) ;
cookie ( '_ha' ) ;
2 将RGB转换为十六进制
const rgbToHex = ( r, g, b ) => "#" + ( ( 1 << 24 ) + ( r << 16 ) + ( g << 8 ) + b) . toString ( 16 ) . slice ( 1 ) ;
rgbToHex ( 0 , 51 , 255 ) ;
3 复制到剪贴板
使用navigator.clipboard.writeText
可以轻松将文本复制到剪贴板
规范要求在写入剪贴板之前使用Permissions API 获取“剪贴板写入”权限。但是,不同的浏览器具体要求不同,因为这是一个新的API。
const copyToClipboard = async ( text ) => {
await navigator. clipboard. writeText ( text) ;
} ;
copyToClipboard ( "Hello Word" ) ;
4 检查日期是否有效
使用以下代码段检查给定日期是否有效
const isDateValid = ( ... val) => ! Number. isNaN ( new Date ( ... val) . valueOf ( ) ) ;
isDateValid ( "December 17, 2009 10:48:15" ) ;
5 查找一年中的某一天
查找给定日期
const dayOfYear = ( date ) => Math. floor ( ( date - new Date ( date. getFullYear ( ) , 0 , 0 ) ) / 1000 / 60 / 60 / 24 ) ;
dayOfYear ( new Date ( ) ) ;
6 大写字符串
JS没有内置的大写函数,但我们可以使用以下代码实现大写
const capitalize = str => str. charAt ( 0 ) . toUpperCase ( ) + str. slice ( 1 ) ;
capitalize ( "come on" ) ;
7 查找两个日期之间的天数
使用以下代码段查找给定两个日期之间的天数
const dayDif = ( date1, date2 ) => Math. ceil ( Math. abs ( date1. getTime ( ) - date2. getTime ( ) ) / 86400000 ) ;
dayDif ( new Date ( "2020-9-20" ) , new Date ( "2020-11-14" ) ) ;
8 清除所有Cookie
使用document.cookie
访问cookie并清除它,从而轻松地清除存储在网页中的所有cookie
const clearCookies = document. cookie. split ( ';' ) . forEach ( cookie => document. cookie = cookie. replace ( / ^ + / , '' ) . replace ( / =.* / , ` =;expires= ${ new Date ( 0 ) . toUTCString ( ) } ;path=/ ` ) ) ;
9 生成随机十六进制
使用Math.random
和padEnd
属性生成随机的十六进制颜色
const randomHex = ( ) => ` # ${ Math. floor ( Math. random ( ) * 0xffffff ) . toString ( 16 ) . padEnd ( 6 , "0" ) } ` ;
console. log ( randomHex ( ) ) ;
10 从数组中删除重复项
使用JS中的Set
轻松删除重复项
const removeDuplicates = ( arr ) => [ ... new Set ( arr) ] ;
console. log ( removeDuplicates ( [ 1 , 2 , 2 , 4 , 4 , 5 ] ) ) ;
11 从URL获取查询参数
通过传递window.location
或原始URLgoole.com?search=se&id=8
从url轻松检索查询参数
const getParmeters = ( URL ) => {
URL = JSON . parse ( '{"' + decodeURI ( URL . split ( "?" ) [ 1 ] ) . replace ( / " / g , '\\"' ) . replace ( / & / g , '","' ) . replace ( / = / g , '":"' ) + '"}' ) ;
return JSON . stringify ( URL ) ;
} ;
12 从日期输出时间
从给定日期以hour::minutes::seconds
的格式输出时间
const timeFromDate = date => date. toTimeString ( ) . slice ( 0 , 8 ) ;
console. log ( timeFromDate ( new Date ( 2021 , 1 , 10 , 5 , 42 , 15 ) ) ) ;
13 检查数字是偶数还是奇数
const isEven = num => num % 2 === 0 ;
console. log ( isEven ( 2 ) ) ;
14 求数字的平均值
使用reduce
方法查找多个数字的平均值
const average = ( ... args) => args. reduce ( ( a, b ) => a + b) / args. length;
average ( 1 , 4 , 5 , 8 ) ;
15 滚动到顶部
使用window.scrollTo(0, 0)
方法自动滚动到顶部
const goToTop = ( ) => window. scrollTo ( 0 , 0 ) ;
goToTop ( ) ;
16 反转字符串
使用split
、reverse
和join
方法反转字符串
const reverse = str => str. split ( '' ) . reverse ( ) . join ( '' ) ;
reverse ( 'hello world' ) ;
17 检查数组是否为空
const isNotEmpty = arr => Array. isArray ( arr) && arr. length > 0 ;
isNotEmpty ( [ 1 , 2 , 3 ] ) ;
18 获取选定的文本
使用内置的getSelection
属性获取用户选择的文本
const getSelectedText = ( ) => window. getSelection ( ) . toString ( ) ;
getSelectedText ( ) ;
19 打乱数组
使用sort
和random
方法打乱数组非常容易
const shuffleArray = ( arr ) => arr. sort ( ( ) => 0.5 - Math. random ( ) ) ;
console. log ( shuffleArray ( [ 1 , 2 , 3 , 4 ] ) ) ;
20 检测暗模式
检测用户的设备是否处于暗模式
const isDarkMode = window. matchMedia && window. matchMedia ( '(prefers-color-scheme: dark)' ) . matches;
console. log ( isDarkMode) ;
21 检查日期是否为周末
const isWeekend = ( date ) => [ 0 , 6 ] . indexOf ( date. getDay ( ) ) !== - 1 ;
console. log ( isWeekend ( new Date ( 2021 , 4 , 15 ) ) ) ;
22 在两个数字之间生成一个随机数
const random = ( min, max ) => Math. floor ( Math. random ( ) * ( max - min + 1 ) + min) ;
console. log ( random ( 1 , 50 ) ) ;
23 生成随机字符串(唯一ID)
如需要临时的唯一ID
const randomString = ( ) => Math. random ( ) . toString ( 36 ) . slice ( 2 ) ;
console. log ( randomString ( ) ) ;
24 切换布尔
const toggleBool = ( ) => ( bool = ! bool) ;
const toggleBool = b => ! b;
25 交换两个变量
let foo = 'foo' ;
let bar = 'bar' ;
console. log ( foo, bar)
[ foo, bar] = [ bar, foo] ;
console. log ( foo, bar)
26 合并多个数组的不同方法
const merge = ( a, b ) => a. concat ( b) ;
const merge = ( a, b ) => [ ... a, ... b] ;
const merge = [ ... new Set ( a. concat ( b) ) ] ;
const merge = [ ... new Set ( [ ... a, ... b] ) ] ;
27 获取js语言的实际类型
const trueTypeOf = ( obj ) => {
return Object . prototype. toString . call ( obj) . slice ( 8 , - 1 ) . toLowerCase ( ) ;
} ;
console. log ( trueTypeOf ( '' ) ) ;
console. log ( trueTypeOf ( 0 ) ) ;
console. log ( trueTypeOf ( ) ) ;
console. log ( trueTypeOf ( null ) ) ;
console. log ( trueTypeOf ( { } ) ) ;
console. log ( trueTypeOf ( [ ] ) ) ;
console. log ( trueTypeOf ( ( ) => { } ) ) ;
28 在结尾处截断字符串
const truncateString = ( string, length ) => {
return string. length < length ? string : ` ${ string. slice ( 0 , length - 3 ) } ... ` ;
} ;
console. log ( truncateString ( 'Hi, you are a good people!' , 36 ) ;
29 从中间截断字符串
const truncateStringMiddle = ( string, length, start, end ) => {
return ` ${ string. slice ( 0 , start) } ... ${ string. slice ( string. length - end) } ` ;
} ;
console. log ( truncateStringMiddle ( 'There are many cats!' , 15 , 7 , 11 ) ) ;
30 检查当前选项卡是否在视图/焦点内
const isTabInView = ( ) => ! document. hidden;
isTabInView ( ) ;
31 检查用户是否在Apple设备上
const isAppleDevice = ( ) => / Mac|iPad|iPhone / . test ( navigator. platform) ;
console. log ( isAppleDevice ( ) ) ;
32 三元运算符
const age = 18 ;
const greetings = age < 18 ? 'ok' : 'not ok' ;
33 短路评估速记
if ( name !== null || name !== undefined || name !== '' ) {
let fullName = name;
}
const fullname = name || 'buddy' ;