Basic usage of Javascript

1. Randomly generate strings
const randomStr = () =>
Math.random().toString(20).slice(2);
randomStr();
2. Realize the flipping of the string
const reverseStr = str =>
str.split('').reverse().join('');
reverStr('vue 入门到精髓');
reverStr('it技术分享技术');
3. Delete duplicate elements in the array
const set = new Set([12,356,56,56,85,45,12,12,13,16,18]);
console.log([...set]);
4. RGB to hexadecimal conversion mechanism
const rgbToHex = (r,g,b)=>"#"+((1<<24)+(r<<16)+(g<<8)+b).toString(16).slice(1);
rgbToHex(255,255,255);
5. Shuffle an array and regroup
const shuffle = array =>array.sort(()=>0.6-Math.random());
shuffle([29,3,56,45,13,40]);
6. Get the time interval (number of days) between two dates
const dayDif =(date1,date2)=>Math.ceil(Math.abs(date1.getTime()-date2.getTime())/86400000)
dayDif(new Date("2022-09-03"),new Date("2023-08-10"))
7. Get the current day of the year
const dayofYearStr = (date)=> Math.floor((date-new Date(date.getFullYear(),0,0))/1000/60/60/24);
dayofYearStr(new Date());
8. Intercept the string length
const splitStr = (string,length)=>string.length < length ? sting:`${string.slice(0,length-3)}...`;
splitStr('vue is good web frame',7);
splitStr('vue is good web frame',10);
9. Determine whether the array is empty
const isNotEmptyArr = arr=>Array.isArray[arr] && arr.length > 0;
isNotEmptyArr([6,66,666]);
isNotEmptyArr([]);
10. Merge two arrays into one array
const merge = (a,b) => a.concat(b);
const a =[1,2,3];
const b = [4,5,6];
merge(a,b);
11. Switch the first letter of the English sentence to uppercase
const capitalizeEverWordStr = str =>str.replace(/\b[a-z]/g,char =>char.tpU[[erCase());
capitalizeEverWordStr('hellow vue is');                                                                           
12. Array delete element
const dropArr = (arr,n=1)=>arr.slice(n);
dropArr([10,20,30,40,50]);
dropArr([10,20,30,40,50],2);
dropArr([10,20,30,40,50],42);
13. Get the time part of the current date
const getTimeFromDate = date=> date.toTimeString().slice(0,8);
getTimeFromDate(new Date());
14. Determine whether it is a json string
const isJson = str =>
try{
Json.parse(str);
    return true;
}catch (e){
return false
}};
isJson('{"name":"小明","address":"苏州"}');
isJson('{"name":"小王","address":"南京"}');
15. Get the current URL
const currentURl = ()=>
window.location.href;
currentURl();

おすすめ

転載: blog.csdn.net/weixin_68522070/article/details/132381399