Some commonly used JavaScript methods

1. Determine whether it is a Node.js environment

 function isNode(){
    
    
    return typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
}

Insert image description hereRun in the browser, as shown above
Insert image description hereRun in Node.js, as shown above

2. Parameter summation

Calculate the sum in the physical and chemical form of the function, and do it in one line of reduce

const sum = (...args) => args.reduce((a,b)=>a+b)

Insert image description here

3.ES6 Set array deduplication

const uniqueArr = (arr) => [...new Set(arr)]

Insert image description here

4. Randomly obtain a hexadecimal color

function getRandomColor(){
    
    
return `#${
      
      Math.floor(Math.random()*0xffffff).toString(16)}`
}

Insert image description here

5. Move the last item of the array to the first

const setLastToFirst = (arr) => arr.unshift(arr.pop())

Insert image description here

6. Hide the middle four digits of the mobile phone number through regular expressions

function hidePhone(tel){
    
    
    return tel.replace(/(\d{3})\d{4}(\d{4})/,'$1****$2')
}

Insert image description here

7. Get a Boolean value randomly

The range of Math,random() is 0-0.99, and 0.5 is used to have a 50% probability in the middle.

function getRomBool(){
    
    
    return 0.5 > Math.random()
}

Insert image description here

8. Extract the year, month, time, etc. in the time in one step

在这里插入代码片

Guess you like

Origin blog.csdn.net/weixin_43426379/article/details/129792327