Home > Web Front-end > JS Tutorial > body text

What are the precautions for using ES6?

php中世界最好的语言
Release: 2018-06-06 10:20:10
Original
1284 people have browsed it

This time I will bring you some precautions when using ES6. The following is a practical case, let’s take a look.

ES6 has been out for several years, and many new features can be cleverly used in projects. I want to list some of them in the hope that they will be useful to you.

If you know some other tips, please leave a message. I'm happy to add them.

1. Mandatory parameters

ES6 provides a default parameter value mechanism, allowing you to set default values ​​for parameters to prevent functions from being called. These parameters were not passed in.

In the following example, we write a required() function as the default value for parameters a and b. This means that if one of the parameters in a or b is not passed a value when called, the required() function will be defaulted and an error will be thrown.

const required = () => {throw new Error('Missing parameter')};
const add = (a = required(), b = required()) => a + b;
add(1, 2) //3
add(1) // Error: Missing parameter.
Copy after login

2. Powerful reduce

The reduce method of arrays is very versatile. It is generally used to reduce each item in an array to a single value. But you can do more with it.

2.1 Use reduce to implement map and filter at the same time

Suppose there is a sequence now, and you want to update each item of it (map function) and then filter out a part ( filter function). If you use map first and then filter, you need to iterate through the array twice.

In the code below, we double the values ​​in the sequence and then select those numbers greater than 50. Notice how we use reduce very efficiently to complete both the map and filter methods?

const numbers = [10, 20, 30, 40];
const doubledOver50 = numbers.reduce((finalList, num) => {
 num = num * 2; 
 if (num > 50) {
  finalList.push(num);
 }
 return finalList;
}, []);
doubledOver50; // [60, 80]
Copy after login

2.2 Use reduce to replace map and filter

If you read the above code carefully, you should be able to understand that reduce can replace map and filter.

2.3 Use reduce to match parentheses

Another use of reduce is to match parentheses in a given string. For a string containing parentheses, we need to know whether the number of (and) is consistent, and whether (appears before).

In the following code we can easily solve this problem using reduce. We only need to declare a counter variable first, with the initial value being 0. Counter increases by one when encountering (, counter decreases by one when encountering). If the number of left and right brackets matches, the final result is 0.

//Returns 0 if balanced.
const isParensBalanced = (str) => {
 return str.split('').reduce((counter, char) => {
  if(counter < 0) { //matched ")" before "("
   return counter;
  } else if(char === &#39;(&#39;) {
   return ++counter;
  } else if(char === &#39;)&#39;) {
   return --counter;
  } else { //matched some other char
   return counter;
  }
  
 }, 0); //<-- starting value of the counter
}
isParensBalanced(&#39;(())&#39;) // 0 <-- balanced
isParensBalanced(&#39;(asdfds)&#39;) //0 <-- balanced
isParensBalanced(&#39;(()&#39;) // 1 <-- not balanced
isParensBalanced(&#39;)(&#39;) // -1 <-- not balanced
Copy after login

2.4 Count the number of identical items in an array

Many times, you want to count the number of recurring items in an array and then represent them with an object. Then you can use the reduce method to process this array.

The following code will count the number of each type of car and then represent the total number with an object.

var cars = [&#39;BMW&#39;,&#39;Benz&#39;, &#39;Benz&#39;, &#39;Tesla&#39;, &#39;BMW&#39;, &#39;Toyota&#39;];
var carsObj = cars.reduce(function (obj, name) { 
  obj[name] = obj[name] ? ++obj[name] : 1;
 return obj;
}, {});
carsObj; // => { BMW: 2, Benz: 2, Tesla: 1, Toyota: 1 }
Copy after login

There are so many other uses for reduce. I recommend you read MDN’s related code examples.

3. Object destructuring

3.1 Delete unnecessary attributes

Sometimes you don’t You want to preserve certain object properties, perhaps because they contain sensitive information or are just too big. You might be able to enumerate the entire object and delete them, but really you just assign the useless properties to variables, and then pass the useful parts you want to keep as the remaining parameters.

In the following code, we want to delete the _internal and tooBig parameters. We can assign them to the internal and tooBig variables, and then store the remaining properties in cleanObject for later use.

let {_internal, tooBig, ...cleanObject} = {el1: '1', _internal:"secret", tooBig:{}, el2: '2', el3: '3'};
console.log(cleanObject); // {el1: '1', el2: '2', el3: '3'}
Copy after login

3.2 Deconstructing nested objects in function parameters

In the following code, engine is an object nested in the object car. If we are interested in the vin attribute of engine, we can easily get it using destructuring assignment.

var car = {
 model: 'bmw 2018',
 engine: {
  v6: true,
  turbo: true,
  vin: 12345
 }
}
const modelAndVIN = ({model, engine: {vin}}) => {
 console.log(`model: ${model} vin: ${vin}`);
}
modelAndVIN(car); // => model: bmw 2018 vin: 12345
Copy after login

3.3 Merging Objects

ES6 brings the spread operator (...). It's typically used to destructure arrays, but you can also use it with objects.

Next, we use the spread operator to expand a new object. The attribute values ​​in the second object will overwrite the attribute values ​​of the first object. For example, b and c of object2 will overwrite the attributes of the same name of object1.

let object1 = { a:1, b:2,c:3 }
let object2 = { b:30, c:40, d:50}
let merged = {…object1, …object2} //spread and re-add into merged
console.log(merged) // {a:1, b:30, c:40, d:50}
Copy after login

4. Sets

4.1 Use Set to implement array deduplication

In ES6 , because Set only stores unique values, you can use Set to remove duplicates.

let arr = [1, 1, 2, 2, 3, 3];
let deduped = [...new Set(arr)] // [1, 2, 3]
Copy after login

4.2 Using array methods on Set

使用扩展运算符就可以简单的将Set转换为数组。所以你可以对Set使用Array的所有原生方法。

比如我们想要对下面的Set进行filter操作,获取大于3的项。

let mySet = new Set([1,2, 3, 4, 5]);
var filtered = [...mySet].filter((x) => x > 3) // [4, 5]
Copy after login

5. 数组解构

有时候你会将函数返回的多个值放在一个数组里。我们可以使用数组解构来获取其中每一个值。

5.1 数值交换

let param1 = 1;
let param2 = 2;
//swap and assign param1 & param2 each others values
[param1, param2] = [param2, param1];
console.log(param1) // 2
console.log(param2) // 1
Copy after login

5.2 接收函数返回的多个结果

在下面的代码中,我们从/post中获取一个帖子,然后在/comments中获取相关评论。由于我们使用的是async/await,函数把返回值放在一个数组中。而我们使用数组解构后就可以把返回值直接赋给相应的变量。

async function getFullPost(){
 return await Promise.all([
  fetch('/post'),
  fetch('/comments')
 ]);
}
const [post, comments] = getFullPost();
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

ajax怎样动态增加表格的tr与td

微信小程序内轮播图怎样设置成自适应高度

The above is the detailed content of What are the precautions for using ES6?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!