This is my 16th day in the More Text Challenge. For more details, see more text Challenge

In order to have more time to feel fish, prepare to write a JS tips series, the main is to sum up some can improve the speed and efficiency of JS tips.

Remove duplicates from an array

const array = [1, 3, 2, 3, 2, 'Axjy', true, false, true, 'Axjy', 1, 3];
const filteredArray = [...new Set(array)];
console.log(filteredArray)
Copy the code

How it works: SETS are only allowed to store duplicate values, so when you put them in an array, it automatically removes duplicate values.

A more concise For loop

const names = ['Axjy','Jin','olivivian']

for(let i = 0; i<names.length; i++){ const name = names[i] console.log(name) }Copy the code

Is equivalent to

for(let name of names) console.log(name)
Copy the code

Null merge operator (??)

Can be used to ensure that the value is not null or undefined

Note: (??) Do not AND directly AND (&) AND OR (| |) together

The optional chain operator (? .).

The optional chain operator will make the expression shorter and more concise when trying to access object properties that may not exist.

Let result = user.employee && User.employee.name; Now just let result = user.employee? By using the?. Operator instead of the. Operator, JavaScript implicitly checks to make sure that user.employee is neither null nor undefined before attempting to access user.employee.name.Copy the code

Reduce nesting if.. Or else the switch case

Function doSomething(){console.log(' execute method ')}Copy the code

Requirement 1: If a certain condition is met, the method is executed

Let a= 6 if(a===6){doSomething()} // ===6 && doSomething()Copy the code

Requirement 2: If a condition is not met, the method is executed

Function doSomething(){console.log(' execute ')} let a = 6 if(a! = = 5) {doSomething ()} / / is equivalent to a = = = 5 | | doSomething ()Copy the code

Fast merge objects

const result = {... arr1, ... arr2, ... arr3}Copy the code

Array destruct swap values

Array summation, maximum, minimum

Const array =,4,7,8,9,2 [5]; Array. Reduce ((a,b) => a+b); // Max. Array. Reduce ((a,b) => a>b? a:b); Array. Reduce ((a,b) => a<b? a:b);Copy the code

stringanddigitalFast interchange (not recommended)

This method is for understanding only, but is not recommended for code readability;

let num = 12 let numString = num + ""; let stringNum = + numString; Console. log(' string to number ',numString,typeof numString) console.log(' string to number ',stringNum,typeof stringNum)Copy the code

Principle: a number plus an empty string becomes a string; Strings are converted to numbers using the plus sign (+).


Just like it before you go! 🤞 🤞 🤞