Share 15 code snippets commonly used in JavaScript work

preface

Original intention:   Sort out the JavaScript tips commonly used in work and share them with you. I hope it can help you to improve development efficiency in your work.

Suitable for people:   Front end primary development, big guys detour.

1. Function parameter default value

Before Es6, if we want to write the default value of parameters, we also need to write a pile of judgment logic in the function body. After Es6, we need to take a look at the new parameter default value syntax.

function person(name, age, sex = "male") {
    console.log(name, age, sex) // Frogman 24 male
}
person("Frogman", 24)

2. Use reduce for array summation

Previously, we used the for loop for ergodic summation, or we can use the reduce method for summation to simplify the code.

let nums = [1,22,31,4,56]
let sum = nums.reduce((prev, cur) => prev + cur, 0)

3. Waste if   else

When we write judgments, we use if   else, but when the business is getting larger and larger, there are several States, so the code is too redundant. Let's simplify it.

if(xxx = 1) {
    xxx = "Enable"
} else if(xxx = 2) {
    xxx = "Deactivate"
}
// ... omitted
// Abolish the above wording

let operation = {
    1: "Enable",
    2: "Deactivate"
    3: "cancellation",
    4: "modify"
    5: "details"
}
xxx = operation[status] // The code is concise and clear

4. Exchange variables

Before Es6, we have to use the third variable when we interact with the variable value. When Es6 deconstructs and assigns values, we can exchange variables very quickly.

let x = 10;
let y = 20;
[x, y] = [y, x];

5. Array de duplication

Before Es6, we used for loop traversal or indexOf for array de duplication, but Es6 has a Set structure, which is very convenient.

let arr = [1,1,2,434,2,1]
console.log([...new Set(arr)]) // 1 2 434

6. Quickly obtain URL address bar parameters

Sometimes we want to get the parameters on the address bar. They are all handwritten methods. There is an Api practical method to process the query string of the URL.

let params = new URLSearchParams(location.search);
params.get("xxx") // Get address bar parameters

7. Generate random Id

In some cases, we can use the following methods to obtain random non repeating strings

Math.random().toString(36).substr(2)

8. Get object key value

Quickly get the key value of the object

let person = {name: "Frogman", age: 24};
console.log(Object.keys(person)) // ["name", "age"]

9. Get object value

Quickly get the value of the object

let person = {name: "Frogman", age: 24};
console.log(Object.values(person)) // ["frogman", 24]

10. Template string expression

Before Es6, our string splicing variables were spliced with the + sign, so the splicing was good. If we spliced html tags, it would be very uncomfortable. If we didn't pay attention, we would report an error symbol. In Es6, the template string is used ` `, and then the variables are bound in ${}, which makes our development very convenient.

let name = "Frogman"
console.log(`hello ${name}`)
console.log(`<p>${name}</p>`)

11. Get the value specified in the object

It is very simple to use object deconstruction to obtain object values, instead of using the traditional syntax to obtain them one by one

const person = {name: "Frogman", age: 24, sex: "male"};
let { age, sex } = person
console.log(age, sex) // 24 male

12. Quickly convert string to array

Instead of using the string split method, you can quickly convert to an array using the extension operator.

let str = "abcdefg"
console.log([...str]) // ["a", "b", "c", "d", "e", "f", "g"]

13. Determine the value by using the three eye operation

If there are only two states, it is strongly recommended to use ternary operation and abandon if else.

let status = 1;
status = status == 1 ? "male" : "female"

14.?? operator

?? Operator, only the previous value is undefined   or   null will be executed. It is used in some cases in work. Let's take a look.

let status = undefined;
let text = status ?? "Not yet"
console.log(text) // Not yet

15.?. operator

?. Operator is sometimes very useful when processing objects. Look at the following case. person.name returns undefined, and then an error will be reported when calling toString. In this case, use Operator will not produce an error Operator is that the toString method is called only when the value is not undefined.

let person = {}
console.log(person.name.toString()) // report errors
console.log(person.name?.toString()) // undefined

If you want to develop applets or learn more about applets, you can help you realize your development needs through a third-party professional development platform: Xiamen cares about technology -Focus Xiamen applet customization development , APP development, website development, H5 game development

Keywords: Javascript html5

Added by prime on Wed, 08 Sep 2021 08:39:55 +0300