今天这篇文章,主要是想和大家分享一些JavaScript单行。在这些方法中,我们使用了一些API来帮助我们简化操作。可能有一些方法写一行不是很优雅。我们这样做的目的主要是为了进一步学习API的使用技巧。希望对你的学习有所帮助。现在,让我们进入今天的内容。1.复制内容到剪贴板constcopyToClipboard=(text)=>navigator.clipboard.writeText(text);copyToClipboard("你好世界");2.清除所有cookiesconstclearCookies=document.cookie.split(';')。forEach(cookie=>document.cookie=cookie.replace(/^+/,'').replace(/=.*/,`=;expires=${newDate(0).toUTCString()};path=/`));3.获取选中的文本constgetSelectedText=()=>window.getSelection().toString();getSelectedText();4.滚动到页面顶部constgoToTop=()=>window.scrollTo(0,0);转到顶部();5.判断当前tab是否激活constisTabInView=()=>!document.hidden;6.判断当前设备是否为苹果设备constisAppleDevice=()=>/Mac|iPod|iPhone|iPad/.test(navigator.platform);isAppleDevice();7.是否滚动到页面底部constscrolledToBottom=()=>document.documentElement.clientHeight+window.scrollY>=document.documentElement.scrollHeight;8.重定向到URLconstredirect=url=>location.href=urlredirect("https://www.google.com/")9.打开浏览器打印框constshowPrintDialog=()=>window.print()10.随机布尔常量randomBoolean=()=>Math.random()>=0.5;随机布尔值();11、变量交换[foo,bar]=[bar,foo];12.获取变量类型consttrueTypeOf=(obj)=>Object.prototype.toString。call(obj).slice(8,-1).toLowerCase();trueTypeOf('');//字符串真实类型(0);//numbertrueTypeOf();//undefinedtrueTypeOf(null);//nulltrueTypeOf({});//objecttrueTypeOf([]);//arraytrueTypeOf(0);//numbertrueTypeOf(()=>{});//功能13.检查对象是否为空constisEmpty=obj=>Reflect.ownKeys(obj)。length===0&&obj.constructor===对象;14.检查日期是否有效constisDateValid=(...val)=>!Number.isNaN(newDate(...val).valueOf());isDateValid("2022年12月17日03:24:00");15.计算两个日期的间隔constdayDif=(date1,date2)=>Math.ceil(Math.abs(date1.getTime()-date2.getTime())/86400000)dayDif(newDate("2022-11-3"),新日期("2023-2-1"));16.找出一年中的第几天constdayOfYear=(date)=>Math.floor((date-newDate(date.getFullYear(),0,0))/1000/60/60/24);dayOfYear(新日期());17.时间格式化consttimeFromDate=date=>date.toTimeString().slice(0,8);timeFromDate(newDate(2022,11,2,12,30,0));timeFromDate(newDate());18.将字符串首字母大写constcapitalize=str=>str.charAt(0).toUpperCase()+str.slice(1)capitalize("helloworld")19.翻转字符串constreverse=str=>str.split('').reverse().join('');反向('你好世界');20.随机字符串constrandomString=()=>Math.random().toString(36).slice(2);randomString();21.截断字符串consttruncateString=(string,length)=>string.length
