I don't want to be sprayed anymore, let's sort out the commonly used es6! !

Start the Nuggets Growth Journey! This is the 7th day of my participation in the "Nuggets Daily New Project · February Update Challenge", click to view the details of the event

Hello everyone, I am Master Lin, a passionate young man who focuses on front-end technology and aspires to become an expert in front-end technology.

Starting from January 17, 2023, I decided to create a new column [Maximum LeetCode], brush at least one LeetCode original question every day, and use Typescript and native JS to write code.

Today is day 3 ヾ(◍°∇°◍)ノ゙

To give you an idea of ​​where I am right now:

That's right, I finished moving this morning, and I rushed over to the company in the afternoon. I'm in charge, and the module still needs to be finished, but it's a pity that the token doesn't have access rights, so I can only ask my colleagues to open the permissions tomorrow.

This is my new home. Before and after the move, I still need to clean up. I hope to improve the atmosphere of the home, so that there is a more learning atmosphere, and maybe it can improve learning efficiency.

My eyes are full of clutter, I can't stand it, go back and tidy up before going to bed! !

But it's not a waste of time, at least I know how to ferry~

Following yesterday's topic, continue to update the es6 syntax commonly used in work:

Judgment statement in if

if(
    type == 1 ||
    type == 2 ||
    type == 3 ||
    type == 4 ||
){
   //...
}
复制代码

After improvement, it can be abbreviated as:

  const condition = [1, 2, 3, 4]  const type = 11  if (condition.includes(type)) {    console.log('这是真的吗')  }
复制代码

list search

In formal project development, when faced with the search function of some lists without pagination, the front end is generally responsible for implementing it.

Search is generally divided into precise search and fuzzy search, and search is also called filtering.

One is fuzzy search, which is generally implemented with filter :

    const a = [1, 2, 3, 4, 5]    const result = a.filter((item) => {      return item === 3    })    console.log('result', result)//[3]
复制代码

However, if it is an exact search, you need to use find in ES6

const a = [1,2,3,4,5];
const result = a.find( 
  item =>{
    return item === 3
  }
)
复制代码

Get object property value

const name = obj && obj.name;
复制代码

You can use the optional chaining operator in ES6:

const name = obj?.name;
复制代码

flatten array

In the development of ERP system or personnel management system, an application scenario is often encountered:

In a department JSON data, the attribute name is the department id, and the attribute value is an array set of department member ids. Now the requirement is to extract all the member ids of the department into an array set:

const deps = {
'数据部':[1,2,3],
'DT部':[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)]
复制代码

At this time, I seem to hear the front-end team leader start to scold:

Do you still need to traverse to get all the property values ​​of the object? Is performance optimization good, Object.values ​​​​forgot? Never used ES6 before? (Soul torture), as well as the flattening of arrays, why not use the flat method provided by ES6?

I... (speechless)

const deps = {
'数据部':[1,2,3],
'DT部':[5,8,12],
'行政部':[5,14,79],
'人事部':[3,64,105],
}
let member = Object.values(deps).flat(Infinity);
复制代码

Infinity is used as the flat parameter, so that you don't need to know the dimensions of the flattened array.

Add object property value

When adding a property to an object, if the property name changes dynamically, what should I do:

let obj = {};
let index = 1;
let key = `topic${index}`;
obj[key] = '话题内容';
复制代码

Why create an extra variable.

(Pointing at me) Don't you know that object property names in ES6 can use expressions?

After improvement:

let obj = {};
let index = 1;
obj[`topic${index}`] = '话题内容';
复制代码

Judgment that the input box is not empty

In daily development, regardless of the PC or mobile terminal, when dealing with business related to the input box, it is often judged that the input box does not enter a value:

if(value !== null && value !== undefined && value !== ''){
    //...
}
复制代码

Can be improved to:

if((value??'') !== ''){
  //...
}
复制代码

Did it save a lot of code, surprise or surprise! ! !

Get object property value

Take a chestnut:

const name = obj && obj.name;
复制代码

After improvement:

const name = obj?.name;
复制代码

async function

Asynchronous functions are very common, go directly to chestnuts:

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)
      })
   })
};
复制代码

Looking at such code, I seem to see the contemptuous eyes of the front-end team leader~

Written like this, what is the difference from callback hell!

After careful improvement:

const fn = async () =>{
  const res1 = await fn1();
  const res2 = await fn2();
  console.log(res1);// 1
  console.log(res2);// 2
}
复制代码

The code is much more concise at once, and I finally breathe a sigh of relief.

If it is a concurrent request, you can use Promise.all()

const fn = () =>{
   Promise.all([fn1(),fn2()]).then(res =>{
       console.log(res);// [1,2]
   }) 
}
复制代码

epilogue

The above is the most commonly used es6 syntax I summarized, and I finally fulfilled my promise.

I recently moved to a new house, and I plan to buy some decorations to decorate my room. Although I rent a house, a good environment will definitely bring a good mood, and maybe the coding will be much faster.

Of course, I still want to own a house of my own, so just buy it in Maoming, my hometown.

My sister bought her own house and car as early as last year, which inspired me a lot, and her home decoration is really ins!

The picture above is a corner of my sister's bedroom. I have to say that the light is really good, full of happiness (*^▽^*)

In the next issue, I will tell the story of my sister and my plan to buy a house in [Laolin Stories Collection].

PS: My sister is still single, I will post a photo of me and my sister in the next issue!

Please look forward ヾ(◍°∇°◍)ノ

Guess you like

Origin juejin.im/post/7201871038443307066