js advanced tips

Check if the date is a working day

const isWeekday = (date) => date.getDay() % 6 !== 0;
console.log(isWeekday(new Date(2021, 2, 15)));

Get random boolean value true/false

const randomBoolean = () => Math.random() >= 0.5;
console.log(randomBoolean());

Reverse string

const reverse = str => str.split('').reverse().join('');
reverse('hello world'); 

Check if the number is even

const isEven = num => num % 2 === 0;
console.log(isEven(2));

Get time from date

const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 2, 15, 19, 30, 0)));

Time without date

var time=/\d{4}-\d{1,2}-\d{1,2}/g.exec('2021-3-15 19:50:00')[0]
// "2021-3-15"

Keep decimal point (not rounded)

const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
toFixed(23.54887845481, 1);       // 23.5
toFixed(23.4648748688, 2);       // 23.46

Scroll to the top of the page

const goToTop = () => window.scrollTo(0, 0);
goToTop();

Get the average of all parameters

const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);

Check if the current user is an Apple device

const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);

Formatting JSON code
We are all very familiar with JSON.stringify, but what we don't know is that it can also format the output.
The stringify method has three parameters: value, replacer and space. Among them, the latter two are optional parameters, which is why we rarely know them. To indent JSON, you must use the space parameter.

console.log(JSON.stringify({name:"yy",Age:23},null,'\t'));
>>> 
{
 "name": "yy",
 "Age": 23
}

Get the unique value from the array

let uniqueArray = [...new Set([423, 43242,342, 333,"666","666",'a','b','c','c',true])]

Remove dummy values ​​from the array

myArray.filter(Boolean)

Combine multiple objects

const summary = {...obj1, ...obj2, ...obj3}

Guess you like

Origin blog.csdn.net/weixin_43881166/article/details/114847959