事不宜迟,我马上开始的,我希望你发现他们对你有帮助!
1.日期是否正确(有效)
此方法用于检查给定日期是否有效
constisDateValid=(...val)=>!Number.isNaN(newDate(...val).valueOf());isDateValid("December27,202213:14:00");//true2.知道一个日期是否对应于当前日期
就像将两个日期转换为相同格式并进行比较一样简单。
是一个Date实例。
constisCurrentDay=(date)=>newDate().toISOString().slice(0,10)===date.toISOString().slice(0,10);3.如何知道一个日期是否在两个日期之间
我们检查过去的日期是否在最小-最大范围内。
constisBetweenTwoDates=(min,max,date)=>date.getTime()>=min.getTime()&&date.getTime()<=max.getTime();4.计算两个日期之间的间隔
此方法用于计算两个日期之间的间隔。
constdayDif=(date1,date2)=>Math.ceil(Math.abs(date1.getTime()-date2.getTime())/86400000)dayDif(newDate("2022-08-27"),newDate("2022-12-25"))//1205.如何知道约会是否在周末
getDay方法返回一个介于0和6之间的数字,表示给定日期是星期几。
constisWeekend=(date)=>date.getDay()===6||date.getDay()===0;6.检查日期是否在一年内
类似于我们过去检查日期是否与当前日期相对应的情况。在这种情况下,我们获取年份并进行比较。
和是两个Date实例。
constisInAYear=(date,year)=>date.getUTCFullYear()===newDate(`${year}`).getUTCFullYear();7.确定日期所在的一年中的哪一天
此方法用于检测给定日期所在的一年中的哪一天。
constdayOfYear=(date)=>Math.floor((date-newDate(date.getFullYear(),0,0))/1000/60/60/24);dayOfYear(newDate());//2398.将小时转换为AM-PM格式
consttimeFromDate=date=>date.toTimeString().slice(0,8);timeFromDate(newDate(2021,11,2,12,30,0));//12:30:00timeFromDate(newDate());//nowtime09:00:0010.将小时转换为AM-PM格式
consttoAMPMFormat=(h)=>`${h%12===012:h%12}${h<12'am.':'pm.'}`;
10.1字符串的初始大写
此方法用于将字符串的第一个字母大写。
constcapitalize=str=>str.charAt(0).toUpperCase()+str.slice(1)capitalize("helloworld")//Helloworld10.2句子首字母大写
我们将第一个字母转换为大写字母,然后使用
constcapitalize=([first,...rest])=>`${first.toUpperCase()}${rest.join('')}`;11.将一封信转换成他的同事表情符号
constletterToEmoji=c=>String.fromCodePoint(c.toLowerCase().charCodeAt()+127365);12.如何判断一个字符串是不是回文
constisPalindrome=(str)=>str.toLowerCase()===str.toLowerCase().split('').reverse().join('');13.翻转字符串
该方法用于翻转字符串并返回翻转后的字符串。
constreverse=str=>str.split('').reverse().join('');reverse('helloworld');//'dlrowolleh'14.随机字符串
此方法用于生成随机字符串。
//方式一constrandomString=()=>Math.random().toString(36).slice(2);randomString();//方式二constrandomstr=Math.random().toString(36).substring(7)15.字符串截断
此方法将字符串截断为指定长度。
consttruncateString=(string,length)=>string.length 此方法用于从字符串中删除HTML元素。 conststripHtml=html=>(newDOMParser().parseFromString(html,'text/html')).body.textContent||'';数字 17.如何计算一个数的阶乘 constgetFactorial=(n)=>(n<=11:n*getFactorial(n-1));18.如何获得一个数的斐波那契数列 constgetFibonacci=(n,memo={})=>memo[n]||(n<=21:(memo[n]=getFibonacci(n-1,memo)+getFibonacci(n-2,memo)));19.如何求一个数的阶乘 constgetFactorial=(n)=>(n<=11:n*getFactorial(n-1));20.判断一个数是奇数还是偶数 此方法用于确定数字是奇数还是偶数。 constisEven=num=>num%2===0;isEven(996);21.得到一组数字的平均值 constaverage=(...args)=>args.reduce((a,b)=>a+b)/args.length;average(1,2,3,4,5);//322.从两个整数中确定随机整数 此方法用于获取两个整数之间的随机整数。 constrandom=(min,max)=>Math.floor(Math.random()*(max—min+1)+min);random(1,50);23.四舍五入到指定位数 此方法可用于将数字四舍五入到指定的数字。 constrandom=(min,max)=>Math.floor(Math.random()*(max—min+1)+min);random(1,50);数组 24.将一个数组复制到另一个数组 constcopyToArray=(arr)=>[...arr];25.从数组中获取唯一元素 constgetUnique=(arr)=>[...newSet(arr)];26.随机排列 以下代码段以非常有效的方式打乱数组。 constshuffle=(arr)=>arr.sort(()=>Math.random()-0.5);27.按属性对数组进行分组 constgroupBy=(arr,groupFn)=>arr.reduce((grouped,obj)=>({...grouped,[groupFn(obj)]:[...(grouped[groupFn(obj)]||[]),obj],}),{});28.检查两个数组是否包含相同的值 我们可以使用Array.sort()和Array.join()方法来检查两个数组是否包含相同的值。 constcontainSameValues=(arr1,arr2)=>arr1.sort().join(',')===arr2.sort().join(','); 29.检测对象是否为空 该方法用于检测JavaScript对象是否为空。 constisEmpty=obj=>Reflect.ownKeys(obj).length===0&&obj.constructor===Object;30.切换变量 可以使用以下形式交换两个变量的值,而无需应用第三个变量。 [foo,bar]=[bar,foo];31.随机布尔值 此方法返回一个随机布尔值。使用Math.random(),你可以得到一个0-1的随机数,并将它与0.5进行比较,有一半的概率得到一个真值或假值。 constrandomBoolean=()=>Math.random()>=0.5;randomBoolean();32.获取变量的类型 该方法用于获取变量的类型。 consttrueTypeOf=(obj)=>Object.prototype.toString.call(obj).slice(8,-1).toLowerCase();trueTypeOf(‘');//stringtrueTypeOf(0);//numbertrueTypeOf();//undefinedtrueTypeOf(null);//nulltrueTypeOf({});//objecttrueTypeOf([]);//arraytrueTypeOf(0);//numbertrueTypeOf(()=>{});//function33.颜色转换 33.1将HEX"#00000"转换为RGB(0,0,0) consttoRGB=(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));33.2将RGB(0,0,0)转换为HEX"#00000" constrgbToHex=(r,g,b)=>"#"+((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1);rgbToHex(255,255,255);//'#ffffff'33.3随机生成一种十六进制颜色 此方法用于获取随机的十六进制(HEX)颜色值。 constrandomHex=()=>`#${Math.floor(Math.random()*0xffffff).toString(16).padEnd(6,"0")}`;randomHex();34.温度与华氏度转换 34.1转换为华氏温度 consttoFahrenheit=(celsius)=>(celsius*9)/5+32;34.2转换为摄氏度 consttoCelsius=(fahrenheit)=>(fahrenheit-32)*5/9;35.确定当前选项卡是否处于活动状态 此方法用于检查当前选项卡是否处于活动状态。 constisTabInView=()=>!document.hidden;36.判断当前设备是否为苹果设备 此方法用于检查当前设备是否为Apple设备。 constisAppleDevice=()=>/Mac|iPod|iPhone|iPad/.test(navigator.platform);isAppleDevice();37.如何清除浏览器的所有cookies constclearAllCookies=()=>document.cookie.split(';').forEach((c)=>(document.cookie=c.replace(/^+/,'').replace(/=.*/,`=;expires=${newDate().toUTCString()};path=/`)));38.检查函数是否为异步函数 constisAsyncFunction=(f)=>Object.prototype.toString.call(f)==='[objectAsyncFunction]';39.如何知道一段代码是否在浏览器中运行 construnningInBrowser=typeofwindow==='object'&&typeofdocument==='object';40.如何知道一段代码是否在node中运行 construnningInNode=typeofprocess!=='undefined'&&process.versions!=null&&process.versions.node!=null;41.检测暗模式 这是一种非常方便的方法来检查用户是否在其浏览器上启用了黑暗模式。 constisDarkMode=window.matchMedia&&window.matchMedia('(prefers-color-scheme:dark)').matchesconsole.log(isDarkMode)42.滚动的元素滚动到顶部 滚动元素的一种单行方法是使用方法。 //方式一consttoTop=(element)=>element.scrollIntoView({behavior:"smooth",block:"start"});43.滚动的元素滚动到底部 consttoBottom=(element)=>element.scrollIntoView({behavior:"smooth",block:"end"});44.导航到页面顶部 此方法用于返回页面顶部。 constgoToTop=()=>window.scrollTo(0,0);goToTop();45.是否滚动到页面底部 该方法用于判断页面是否在底部。 constscrolledToBottom=()=>document.documentElement.clientHeight+window.scrollY>=document.documentElement.scrollHeight;46.将JSON转换为map 这个函数可以让我们以简单的方式将Map对象转换为JSON字符串。 constjsonToMap=(json)=>newMap(Object.entries(JSON.parse(json)));47.生成一个128位的UUID 此函数允许我们生成具有128位值的UUID,用于唯一标识对象或实体。 constgenerateUUID=(a)=>a(a^((Math.random()*16)>>(a/4))).toString(16):([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,generateUUID);48.重定向到一个URL 此方法用于重定向到新URL。 该方法用于打开浏览器的打印框。 constshowPrintDialog=()=>window.print()50.删除所有cookies 该方法使用document.cookie访问cookie并清除网页上存储的所有cookie。 constclearCookies=document.cookie.split(';').forEach(cookie=>document.cookie=cookie.replace(/^+/,'').replace(/=.*/,`=;expires=${newDate(0).toUTCString()};path=/`));