Home>Article>Web Front-end> 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;or
const f = obj.a + obj.d; const g = obj.c + obj.e;Tucao: "Don't you use ES6's destructuring assignment to get the value? Use 1 for 5 lines of code Isn’t it nice to do it in just one line of code? Just use the object name plus the attribute name to get the value. If the object name is short, it’s okay, but what if it’s very long? This object name will be everywhere in the code.”
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 beundefinedor
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 ES6includesbe 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 usefindin ES6? Do you understand performance optimization? If an item that meets the conditions is found in the
findmethod, 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
flatmethod 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);Using
Infinityas the parameter of
flateliminates the need to know the dimensions of the flattened array .
Supplement
flatmethod 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!