preface

Original intention: I would like to share some common JavaScript tips in my work with you, hoping to help you to improve the development efficiency in your work.

For whom: Front end primary development, big guy detour.

1. Default values of function parameters

Before Es6, we had to write parameter defaults, we had to write a bunch of judgment logic inside the function, but after Es6, we have parameter default syntax, so let’s take a look at that.

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

2. Use Reduce to sum arrays

So far we’ve been using the for loop to iterate and sum, and we can also use the Reduce method to sum, clean code.

let nums = [1.22.31.4.56]
let sum = nums.reduce((prev, cur) = > prev + cur, 0)
Copy the code

3. The abandonedif elsespiderman

We’re always going to use if else when we’re writing judgments, but as the business gets bigger and bigger and there are several states, it becomes redundant, so let’s simplify it a little bit.

if(xxx = 1) {
    xxx = "Enable"
} else if(xxx = 2) {
    xxx = "Stop"
}
/ /... omit
// Do away with the above

let operation = {
    1: "Enable".2: "Stop"
    3: "Cancel".4: "Change"
    5: "Details"
}
xxx = operation[status] // The code is simple and clear
Copy the code

4. Swap variables

Before Es6, we had to use a third variable when we interacted with the values of variables, and when there was deconstruction assignment in Es6, we could swap variables very quickly.

let x = 10;
let y = 20;
[x, y] = [y, x];
Copy the code

5. De-duplicate arrays

Before Es6, we used for loop traversal, indexOf, etc., but Es6 has a Set structure, which is very convenient.

If you don’t understand the Set structure, check out my previous article “Understanding the Set of Data Structures in 5 minutes!”

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

6. Quickly obtain the URL address bar parameters

Sometimes we want to get the parameters in the address bar, all handwritten methods, there is an Api practical way to handle the QUERY string of the URL.

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

7. Generate a random Id

In cases where we want to get random, non-repeating strings, we can use the following method

Math.random().toString(36).substr(2)
Copy the code

8. Obtain the key value of the object

Quickly get the key value of an object

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

9. Obtain the value of the object

Quickly obtain the value of an object

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

10. Template string expression

Before Es6, we used to concatenate strings and variables with a + sign, which was fine, but it was very uncomfortable to concatenate HTML tags, and if you didn’t pay attention to it, you would report error symbols. Es6 has a template string using ‘ ‘, and then ${} inside the binding variable, so that we develop very convenient.

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

Gets the value specified in the object

Using object destructuring to get the value of an object is very simple and not used in the traditional way. Syntax one at a time

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

12. Quickly convert strings to arrays

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"]
Copy the code

13. Use triplet operations to determine values

It is strongly recommended to use triplex operations if there are only two states, discarding the if else.

let status = 1;
status = status == 1 ? "Male" : "Female"
Copy the code

14.??The operator

?? The operator will only be executed if the preceding value is undefined or null, which is used in the case of work. Let’s take a look.

let status = undefined;
let text = status ?? "No."
console.log(text) / / no
Copy the code

15.? .The operator

? The.operator, which is very useful sometimes when you’re dealing with objects, so in this case, person.name returns undefined and then when you call toString you’re sure to get an error, so use?. Operator will not generate errors,? The. Operator is that the toString method is called only if the value is not undefined.

let person = {}
console.log(person.name.toString()) / / an error
console.log(person.name?.toString()) // undefined
Copy the code

16.~ ~Double non operators

The ~~ double non operator can be used to round down.

console.log(~~4.3) / / 4
Copy the code

17. Merge objects

If there are duplicate values in the Object, then the next one overwrites the first one and an infinite number of arguments can be accepted. It’s also used a lot at work.

let person = {name: "Frogman".age: 24}
let obj = Object.assign({}, person)
console.log(obj) // {name: "frogman ", age: 24}
Copy the code

18. Whether the values in the array meet a requirement

The current method returns true if one of the values in the array meets the requirement, and false otherwise.

let list = [1.2.2.2.2.2]
let res = list.some(item= > item > 1)
console.log(res) // true
Copy the code

19. Whether all the values in the array meet the requirements

We used for to check whether all the values in the current array meet the requirements, and we also declared a variable to accumulate them. We just used every to return true if all the values meet the requirements, and false otherwise

let list = [1.2.2.2.2.2]
let res = list.every(item= > item > 1)
console.log(res) // false
Copy the code

20. Randomly shuffling the array order

Sometimes our scene needs to get an array out of order.

let list = [1.2.'frogman'.1.34.3.12]
let res = list.sort(() = > Math.random() - 0.5)
console.log(res)
Copy the code

21. Event delegation

Before, we had 100 Li elements, all of which had to be bound to an onclick event, so it didn’t perform very well, so we could do that with event delegates.

ul.on("click"."li".e= >{... Omit operation})Copy the code

22. Check whether the value is an array

let arr = []
console.log(Array.isArray(arr)) // true
console.log(Object.prototype.toString.call(arr) == "[object Array]") // true
Copy the code

23. Convert pseudo-array to true array

A pseudo-array cannot call a method on a true array object, so you have to convert the pseudo-array to a true array, and get the JS element as a pseudo-array.

document.querySelectAll("div") // NodeList[div, div, div, div]
[...document.querySelectorAll('div')] // Convert to a true array
Array.from(document.querySelectorAll('div')) // Convert to a true array
Copy the code

24. Get the timestamp quickly

console.log(+ new Date())
console.log(Date.now())
Copy the code

Get the index of a value

Before Es6, we only used indexOf to get the index. After Es6, there was another method that returned the indexOf the current value if it was found. If it was not found, it returned -1

let colors = ["red"."blue"."green"]
function getIndex(val) {
    return colors.findIndex(i= > i == val)
}
getIndex("blue") / / 1
Copy the code

26. Convert arrays to objects

In cases where you need to convert an array to an object, you can do so.

Let person = [" person ", 24, "male"] let person = {} person. ForEach (item => (item = item))Copy the code

27. Is it even

let num = val= > val % 2= =0;
num(10) / / true even
num(1) / / false odd
Copy the code

28. Check whether the current page is hidden

Detects whether the current page is hidden, and displays true when switching pages, false is open. It is usually used at work to determine how long the user spends on the page.

document.addEventListener("visibilitychange".function() {
   console.log(document.hidden);
});
Copy the code

29. Remove false values from the current array

Filter out the false values in the array.

let list = ["".false.1.null.undefined."Frogman".24]
let res = item= > item.filter(Boolean)
console.log(res(list))
Copy the code

30. This point

Sometimes we don’t want this to be this value, so we need to change this to point to, there are many ways to change this, arrow function, bind, apply, call, I show here, friends can choose which method to use according to different business scenarios!

let person = {name: "Frogman"}
ul.onclick = (function(e) {
    console.log(this.name )
}).bind(person)
Copy the code

31. Check whether the address is valid

function IsUrl(val) {
    try {
    	if (new URL(val)) {
    	    return true}}catch(e) {
    	return false
    }
}
IsUrl("https://www.baidu.cn") // true
IsUrl("www.baidu.cn") // false
Copy the code

32. Use Map to make the array return the result directly

Sometimes when we’re processing an array and want to return the finished result, rather than reassembling an array, a Map comes into play.

let person = [10, 20, 30]
function fn(item) {
	return item + 1
}
let res = person.map(fn)
console.log(res) // [11, 21, 31]
Copy the code

Thank you

Thank you in spite of your busy schedule to open this article, I hope you can be helpful, if there is a problem welcome to corrections.

I am frogman, if you think this is ok, please click like.

Interested partners can join [front end entertainment circle exchange group] welcome everyone to exchange and discuss

Previous high praise good article

Understand data Structures Set in 5 minutes!

【 Suggestions 】 Share some Git commands commonly used in work and how to solve special problems

Deconstruction: Making Data Access Easier!

Do you really understand the functional features in ES6?

Var, let, const