Preface
original intention: sort out the JavaScript tips commonly used in work to share with you, hoping to help all the friends, improve development efficiency in the work.
suitable for the crowd: front-end primary development, big guys detour.
1. Default value of function parameters
Before Es6, if we want to write parameter default values, we also need to write a bunch of judgment logic in the function body. After Es6, the new parameter default value syntax, let's take a look.
function person(name, age, sex = "male") {
console.log(name, age, sex) // 蛙人 24 male
}
person("蛙人", 24)
2. Array summation uses reduce
Before, we all used the for loop to traverse and sum, and we can also use the reduce method to sum, and the code is concise.
let nums = [1,22,31,4,56]
let sum = nums.reduce((prev, cur) => prev + cur, 0)
3. Abandoned if
else
Man
When we write judgments, we always 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 = "启用"
} else if(xxx = 2) {
xxx = "停用"
}
// ...省略
// 废除以上写法
let operation = {
1: "启用",
2: "停用"
3: "注销",
4: "修改"
5: "详情"
}
xxx = operation[status] // 代码简洁清晰
4. Swap variables
Before Es6, we had to use the third variable when interacting variable values. When Es6 appeared destructuring assignment, we could exchange variables very quickly.
let x = 10;
let y = 20;
[x, y] = [y, x];
5. Array deduplication
Before Es6, we used for loop traversal or indexOf for array deduplication, but Es6 has a Set structure, which is very convenient.
If you don’t understand the Set structure, you can read my last article "Understanding the Set of Data Structure, it only takes 5 minutes! 》
let arr = [1,1,2,434,2,1]
console.log([...new Set(arr)]) // 1 2 434
6. Quickly get URL address bar parameters
Sometimes we want to get the parameters on the address bar, which 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") // 获取地址栏参数
7. Generate random Id
In some cases, we want to get random non-repeating strings, we can use the following method
Math.random().toString(36).substr(2)
8. Get the object key value
Get the key value of the object quickly
let person = {name: "蛙人", age: 24};
console.log(Object.keys(person)) // ["name", "age"]
9. Get the value of the object
Get the value of the object quickly
let person = {name: "蛙人", age: 24};
console.log(Object.values(person)) // ["蛙人", 24]
10. Template string expression
Before Es6, we used the + sign to splice variables in our string splicing. This splicing is fine. If the html
tag is spliced, it will be very uncomfortable. If you don't pay attention to it, you will get a wrong symbol. Es6 appeared template string use ``, and then bind variables in ${}, which makes our development very convenient.
let name = "蛙人"
console.log(`hello ${name}`)
console.log(`<p>${name}</p>`)
11. Get the value specified in the object
Using object destructuring to obtain object values is very concise, you don’t need to use .
grammar to get them one by one like the traditional way.
const person = {name: "蛙人", age: 24, sex: "male"};
let { age, sex } = person
console.log(age, sex) // 24 male
12. Quickly convert a string to an array
split
method is no longer used, and the spread operator can be quickly converted to an array.
let str = "abcdefg"
console.log([...str]) // ["a", "b", "c", "d", "e", "f", "g"]
13. Use trinocular arithmetic to judge the value
If there are only two states, it is strongly recommended to use trinocular operation and discard if else.
let status = 1;
status = status == 1 ? "男" : "女"
14. ??
operator
??
operator will only be executed if the previous value is undefined
or null
. It is used in some cases in the work, let's take a look.
let status = undefined;
let text = status ?? "暂无"
console.log(text) // 暂无
15. ?.
operator
?.
operator This is very useful when dealing with objects sometimes. Look at the following example. person.name
returns undefined
and then calls toString
Then there will be an error. At this time, using the ?.
operator will not cause an error. The ?.
operator is only on the value not undefined
will be called when the toString
method.
let person = {}
console.log(person.name.toString()) // 报错
console.log(person.name?.toString()) // undefined
16. ~~
double NOT operator
~~
double NOT operator can be used to round down.
console.log(~~4.3) // 4
17. Merge objects
Use the new method Object.assign
to merge the object. If there are duplicate values in the object, the back will cover the front and you can receive unlimited parameters. It is also often used in work.
let person = {name: "蛙人", age: 24}
let obj = Object.assign({}, person)
console.log(obj) // {name: "蛙人", age: 24}
18. Does the value in the array meet a requirement?
The current method returns true as long as there is a value in the array that meets the requirements, otherwise false.
let list = [1,2,2,2,2,2]
let res = list.some(item => item > 1)
console.log(res) // true
19. Do all the values in the array meet the requirements?
We used for to traverse to determine whether the values in the current array meet the requirements, and also declare a variable to accumulate. We directly use every
true
when all the requirements are met, otherwise it returns false
let list = [1,2,2,2,2,2]
let res = list.every(item => item > 1)
console.log(res) // false
20. Randomly shuffle the array order
Sometimes our scene needs to disrupt the order of an array.
let list = [1,2,'蛙人', 1, 34, 3, 12]
let res = list.sort(() => Math.random() - 0.5)
console.log(res)
21. Event delegation
Before we had 100 li
, we must bind a onclick
event, so the performance is not very good, we can achieve through event delegation.
ul.on("click", "li", e => {
....省略 操作
})
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
23. Convert pseudo array to true array
Pseudo arrays cannot call methods on real array objects, so you have to convert pseudo arrays to true arrays, and get js elements as pseudo arrays.
document.querySelectAll("div") // NodeList[div, div, div, div]
[...document.querySelectorAll('div')] // 转换为真数组
Array.from(document.querySelectorAll('div')) // 转换为真数组
24. Get the timestamp quickly
console.log(+ new Date())
console.log(Date.now())
25. Get the subscript of a value
Before Es6, we only knew that we used the indexOf
method to get the subscript. After Es6, there is another method. If the value is found to return the current value of the subscript, the return -1 is not found.
let colors = ["red", "blue", "green"]
function getIndex(val) {
return colors.findIndex(i => i == val)
}
getIndex("blue") // 1
26. Convert Array to Object
In some cases, you need to convert the array to an object, you can do so.
let person = ["蛙人", 24, "male"]
let obj = {}
person.forEach(item => (obj[item] = item))
27. Whether it is an odd and even number
let num = val => val % 2 == 0;
num(10) // ture 偶数
num(1) // false 奇数
28. Detect whether the current page is hidden
Monitor whether the current page is hidden. When the page is true
false
is displayed, and 06135ca9521e7f is the open state. Generally, the work is mainly used for how long the user stays on the page.
document.addEventListener("visibilitychange", function() {
console.log(document.hidden);
});
29. Remove the false value in the current array
Filter out the false values in the array.
let list = ["", false, 1, null, undefined, "蛙人", 24]
let res = item => item.filter(Boolean)
console.log(res(list))
30.this points to
Sometimes we don’t want this
be this value, so we have to change the this
, and there are many ways this
arrow function,
bind
, apply
, call
, I will demonstrate one here, friends can choose which to use according to different business scenarios Kind of method!
let person = {name: "蛙人"}
ul.onclick = (function(e) {
console.log(this.name )
}).bind(person)
31. Determine 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
32. Use Map to make the array return the result directly
Sometimes when we deal with arrays, we want to directly return the processed results instead of recombining an array, and then Map comes on the scene.
let person = [10, 20, 30]
function fn(item) {
return item + 1
}
let res = person.map(fn)
console.log(res) // [11, 21, 31]
grateful
Thank you for reading, if you have any help, please pay attention and bookmark it
If you think it is helpful, you can follow the front-end entertainment circle public account, and push a little knowledge for you every day
You can also add me to WeChat make friends, you can chat with me or pull you into the technical exchange group
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。