You said you can use ES6, then use it quickly!
This article will share with you ten comments from a leader about ES6, and add some relevant knowledge accordingly. I hope it will be helpful to everyone!
"If you know how to use ES6, then use it!": This is a leader's "roar" to the team members during a code review meeting. The reason is that During the code review, we found that many places still use the ES5 writing method. This does not mean that the ES5 writing method cannot be used and there will be bugs. It just causes an increase in the amount of code and poor readability.
It just so happened that this leader had a code fetish. He was extremely dissatisfied with members who had 3 to 5 years of experience writing code at this level and kept complaining about the code. However, I feel that I still gained a lot from his complaints, so I recorded the leader’s complaints and shared them with fellow diggers. If you think they are useful, give them a thumbs up. If there are errors or better ways of writing, you are very welcome to comment. Leave a message. [Related recommendations: javascript learning tutorial]
ps: JS syntax after ES5 is collectively called ES6! ! !
1. Complaints about value acquisition
Value acquisition is very common in programs, such as from objectobj# Get the value in ##.
const obj = { a:1, b:2, c:3, d:4, e:5, }
Tucao:
const a = obj.a; const b = obj.b; const c = obj.c; const d = obj.d; const e = obj.e;
const f = obj.a + obj.d; const g = obj.c + obj.e;
Improvement:
const {a,b,c,d,e} = obj; const f = a + d; const g = c + e;
Rebuttal
It’s not that I don’t use ES6’s destructuring assignment, but that the attribute names in the data object returned by the server are not what I want. To get the value in this way, you have to re-create a traversal assignment.Tucao
It seems that your grasp of ES6 destructuring assignment is not thorough enough. If the name of the variable you want to create is inconsistent with the property name of the object, you can write like this:const {a:a1} = obj; console.log(a1);// 1
Supplementary
Although the destructuring assignment of ES6 is easy to use. However, please note that the destructured object cannot beundefined or
null. Otherwise, an error will be reported, so the destructured object must be given a default value.
const {a,b,c,d,e} = obj || {};
2. Comments on merging data
For example, merging two arrays and merging two objects.const a = [1,2,3]; const b = [1,5,6]; const c = a.concat(b);//[1,2,3,1,5,6] const obj1 = { a:1, } const obj2 = { b:1, } const obj = Object.assign({}, obj1, obj2);//{a:1,b:1}
Tucao
Have you forgotten the spread operator in ES6, and do you not consider deduplication when merging arrays?Improvement
const a = [1,2,3]; const b = [1,5,6]; const c = [...new Set([...a,...b])];//[1,2,3,5,6] const obj1 = { a:1, } const obj2 = { b:1, } const obj = {...obj1,...obj2};//{a:1,b:1}
3. Comments on splicing strings
const name = '小明'; const score = 59; let result = ''; if(score > 60){ result = `${name}的考试成绩及格`; }else{ result = `${name}的考试成绩不及格`; }
Tucao
It’s better not to use ES6 string templates like you do. You have no idea what operations can be done in${}. In
${}, you can put any JavaScript expression, perform operations, and reference object properties.
Improvement
const name = '小明'; const score = 59; const result = `${name}${score > 60?'的考试成绩及格':'的考试成绩不及格'}`;
4. Comments on the judgment conditions in if
if( type == 1 || type == 2 || type == 3 || type == 4 || ){ //... }
Tucao
Will the array instance method in ES6includes be used?
Improvement
const condition = [1,2,3,4]; if( condition.includes(type) ){ //... }
5. Comments on list search
In the project, some The search function of non-paginated lists is implemented by the front end. Search is generally divided into precise search and fuzzy search. Search is also called filtering, which is generally implemented usingfilter.
const a = [1,2,3,4,5]; const result = a.filter( item =>{ return item === 3 } )
Tucao
If it is a precise search, wouldn’t you usefind in ES6? Do you understand performance optimization? If an item that meets the conditions is found in the
find method, it will not continue to traverse the array.
Improvement
const a = [1,2,3,4,5]; const result = a.find( item =>{ return item === 3 } )
6. Comments on flattened arrays
A part of JSON data , the attribute name is the department id, and the attribute value is an array collection of department member ids. Now we need to extract all the member ids of the department into an array collection.const deps = { '采购部':[1,2,3], '人事部':[5,8,12], '行政部':[5,14,79], '运输部':[3,64,105], } let member = []; for (let item in deps){ const value = deps[item]; if(Array.isArray(value)){ member = [...member,...value] } } member = [...new Set(member)]
Tucao
Do I still need to traverse to get all the attribute values of the object?Object.valuesForgot? There is also the flattening process involving arrays. Why not use the
flat method provided by ES6? Fortunately, the depth of the array this time is only up to 2 dimensions, and there are also 4- and 5-dimensional depths. Do I need to loop nested loops to flatten the array?
Improvement
const deps = { '采购部':[1,2,3], '人事部':[5,8,12], '行政部':[5,14,79], '运输部':[3,64,105], } let member = Object.values(deps).flat(Infinity);
Infinity as the parameter of
flat eliminates the need to know the dimensions of the flattened array .
Supplement
flat method does not support IE browser.
7. Tucao about getting the object attribute value
const name = obj && obj.name;
Tucao
In ES6 Will the optional chaining operator be used?Improvement
const name = obj?.name;
8. Comments on adding object attributes
当给对象添加属性时,如果属性名是动态变化的,该怎么处理。
let obj = {}; let index = 1; let key = `topic${index}`; obj[key] = '话题内容';
吐槽
为何要额外创建一个变量。不知道ES6中的对象属性名是可以用表达式吗?
改进
let obj = {}; let index = 1; obj[`topic${index}`] = '话题内容';
九、关于输入框非空的判断
在处理输入框相关业务时,往往会判断输入框未输入值的场景。
if(value !== null && value !== undefined && value !== ''){ //... }
吐槽
ES6中新出的空值合并运算符了解过吗,要写那么多条件吗?
if((value??'') !== ''){ //... }
十、关于异步函数的吐槽
异步函数很常见,经常是用 Promise 来实现。
const fn1 = () =>{ return new Promise((resolve, reject) => { setTimeout(() => { resolve(1); }, 300); }); } const fn2 = () =>{ return new Promise((resolve, reject) => { setTimeout(() => { resolve(2); }, 600); }); } const fn = () =>{ fn1().then(res1 =>{ console.log(res1);// 1 fn2().then(res2 =>{ console.log(res2) }) }) }
吐槽
如果这样调用异步函数,不怕形成地狱回调啊!
改进
const fn = async () =>{ const res1 = await fn1(); const res2 = await fn2(); console.log(res1);// 1 console.log(res2);// 2 }
补充
但是要做并发请求时,还是要用到Promise.all()
。
const fn = () =>{ Promise.all([fn1(),fn2()]).then(res =>{ console.log(res);// [1,2] }) }
如果并发请求时,只要其中一个异步函数处理完成,就返回结果,要用到Promise.race()
。
十一、后续
欢迎来对以上十点leader的吐槽进行反驳,你的反驳如果有道理的,下次代码评审会上,我替你反驳。
此外以上的整理内容有误的地方,欢迎在评论中指正,万分感谢。
本文转载自:https://juejin.cn/post/7016520448204603423
作者:红尘炼心
【相关视频教程推荐:web前端】
The above is the detailed content of You said you can use ES6, then use it quickly!. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











In ES6, you can use the reverse() method of the array object to achieve array reversal. This method is used to reverse the order of the elements in the array, putting the last element first and the first element last. The syntax "array.reverse()". The reverse() method will modify the original array. If you do not want to modify it, you need to use it with the expansion operator "...", and the syntax is "[...array].reverse()".

async is es7. async and await are new additions to ES7 and are solutions for asynchronous operations; async/await can be said to be syntactic sugar for co modules and generator functions, solving js asynchronous code with clearer semantics. As the name suggests, async means "asynchronous". Async is used to declare that a function is asynchronous; there is a strict rule between async and await. Both cannot be separated from each other, and await can only be written in async functions.

As JavaScript applications increase in complexity and size, handling asynchronous operations becomes increasingly important. In Vue3, we can use the async and await keywords to handle asynchronous functions, making our code smoother and easier to maintain. This article will introduce the asynchronous function processing method in Vue3 to make your code smoother. async and await keywords In Vue3, we can use the async and await keywords to handle asynchronous operations. async function returns

For browser compatibility. As a new specification for JS, ES6 adds a lot of new syntax and API. However, modern browsers do not have high support for the new features of ES6, so ES6 code needs to be converted to ES5 code. In the WeChat web developer tools, babel is used by default to convert the developer's ES6 syntax code into ES5 code that is well supported by all three terminals, helping developers solve development problems caused by different environments; only in the project Just configure and check the "ES6 to ES5" option.

Method of splicing strings: 1. Use the "+" sign to splice, the syntax is "str = str1 + str2"; 2. Use the sprintf() function of the fmt package to splice, the syntax is "str = fmt.Sprintf("%s%d% s", s1, i, s2)"; 3. Use the join function to splice; 4. Use the WriteString() function of the buffer package to splice; 5. Use the buffer package's Builder() function to splice.

In es5, you can use the for statement and indexOf() function to achieve array deduplication. The syntax "for(i=0;i<array length;i++){a=newArr.indexOf(arr[i]);if(a== -1){...}}". In es6, you can use the spread operator, Array.from() and Set to remove duplication; you need to first convert the array into a Set object to remove duplication, and then use the spread operator or the Array.from() function to convert the Set object back to an array. Just group.

Steps: 1. Convert the two arrays to set types respectively, with the syntax "newA=new Set(a);newB=new Set(b);"; 2. Use has() and filter() to find the difference set, with the syntax " new Set([...newA].filter(x =>!newB.has(x)))", the difference set elements will be included in a set collection and returned; 3. Use Array.from to convert the set into an array Type, syntax "Array.from(collection)".

In es6, the temporary dead zone is a syntax error, which refers to the let and const commands that make the block form a closed scope. Within a code block, before a variable is declared using the let/const command, the variable is unavailable and belongs to the variable's "dead zone" before the variable is declared; this is syntactically called a "temporary dead zone". ES6 stipulates that variable promotion does not occur in temporary dead zones and let and const statements, mainly to reduce runtime errors and prevent the variable from being used before it is declared, resulting in unexpected behavior.
