search
HomeWeb Front-endJS TutorialYou said you can use ES6, then use it quickly!

You said you can use ES6, then use it quickly!

Apr 13, 2022 am 09:46 AM
es6asynchronous functionConcatenate strings

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!

You said you can use ES6, then use it quickly!

"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 be

undefined 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 ES6

includes 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 using

filter.

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 use

find 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);

Using

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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.