Common JavaScript tips

       This article is an article I saw on WeChat and may be used in the future. If there is an infringement, please notify me, thank you guys

1. Randomly generate boolean values

Math.random() will return a random number before 0 to 1, so it can be judged by whether it is greater than 0.5

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

2. Reverse the string

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

3. Determine whether the browser Tab window is the active window

const isBrowserTabInView = () =>document.hidden;

4. Get the time part of the date object

The .toTimeString() method of the date object can get the string in time format, and intercept the previous part

const timeFromDate = data => data.toTimeString().slice(0,8);

5. Numbers are truncated to decimal places

If you need to truncate the decimal places of floating-point numbers (not rounding), you can use Math.pow() to achieve:

const toFixed = (n,fixed)=>~~(Math.pow(10,fixed)*n)/Math.pow(10,fixed);
//Examples
toFixed(26.28382368,1);//16.2
toFixed(26.28382368,2);//16.28
//支持四舍五入的方法
//number 为入参想要转换的值
function round2(number,fixed){
    
      
   with(Math){
    
      
        return round(number*pow(10,fixed))/pow(10,fixed);  
    }  
} 

6. Determine whether the DOM element has been focused

const elementIsInFocus = (el) => (el === document.activeElement);

7. Determine whether the current environment supports touch events

const touchSupported = () => {
    
    
('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
会直接返回值布尔值

8. Determine whether it is an Apple device

//isAppleDevice 布尔值
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);

9. Scroll to the top of the page

The window.scrollTo() method accepts two parameters, x and y, which are used to specify the position of the scroll target, all set to 0, you can return to the top of the page: Note: IE does not support

window.scrollTo(0,0)

10. Find the average

const average = (...args) => args.reduce((a,b) => (a+b)/args.length)

Guess you like

Origin blog.csdn.net/lbchenxy/article/details/114130073