Understanding and usage scenarios of ES6 extension operators

Understanding and usage scenarios of ES6 extension operators

The spread operator, i.e. the ... operator, is a new syntax added to es6. Its main function is to expand arrays or objects (this statement may not be accurate). I hope the following summary will help you understand how to use it.

My personal understanding and summary of the usage scenarios are as follows:

1. Replace the apply method, generally process parameters when calling the function

Assume that our parameter is an array (we will not discuss single parameters here, just pass them in one by one);

var args = [1, 2, 3];

Then we need to return the sum of all elements in this parameter array, so the ES5 approach is as follows:

function addFun(x, y, z) {
    return x + y + z;
}

var args = [1, 2, 3];

// Two calling methods // 1. This method can be used with fewer parameters, but it is unreliable when there are too many parameters.
addFun(args[0], args[1], args[2])

// 2. Use the apply method to directly pass the array addFun.apply(null, args);

The apply method can solve the problem of too many parameters very well, but the premise is that you need to clearly distinguish between the apply and call methods. It is estimated that many students rarely use the apply method.

ES6 uses the spread operator which is much simpler:

function addFun(x, y, z) {
    return x + y + z;
}

var args = [1, 2, 3];

addFun(...args);

Here, the ... operator breaks the args array into individual elements for calculation.

2. Rest parameters (rest operator), mainly for function parameters

The rest operator and the spread operator both have the same name..., but they are used differently. It can be simply understood that the rest operator and the spread operator are opposites. The spread operator expands an array or object, while the rest operator "merges" multiple elements together.

Mainly used for indefinite parameters, it can be understood as a substitute for arguments, so ES6 no longer uses the arguments object

let demoFun = function(...args) {
    for (let item of args) {
        console.log(item);
    }
}

demoFun(1, 2, 3) // 1, 2, 3
let demoFun = function(argA, ...args) {
    console.log(argA);
    console.log(args)
}

demoFun(1, 2, 3);
// 1
// [twenty three]

When used with a structure, just think of it as a whole element.

var [a, ...rest] = [1, 2, 3, 4];

// Here, ...rest is considered as an element. console.log(a) // 1
console.log(...rest) // [2, 3, 4]

3. Data connection and merging

Concatenate arrays and use push to add an array to the end of another array

var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];

// ES5 processing method Array.prototype.push.apply(arr1, arr2);
console.log(arr1) // [1, 2, 3, 4, 5, 6]

// ES6 processing method arr1.push(...arr2);
console.log(arr1) // [1, 2, 3, 4, 5, 6]

Merge arrays (instead of concat method)

var arr1 = ['a', 'b', 'c'];
var arr2 = ['d', 'e', ​​'f'];

// ES5 concatenation var es5Arr = arr1.concat(arr2);
console.log(es5Arr) // ['a', 'b', 'c', 'd', 'e', ​​'f']

// ES6 merge var es6Arr = [...arr1, ...arr2];
console.log(es6Arr) // ['a', 'b', 'c', 'd', 'e', ​​'f']

4. Copying arrays and objects

Array copy

var arr1 = [1, 2, 3];
var arr2 = [...arr1];

console.log(arr1 === arr2) // false

arr2.push(4); // Modifying arr2 will not affect the value of arr1 console.log(arr1); // [1, 2, 3]
console.log(arr2); // [1, 2, 3, 4]

The same goes for objects

var obj1 = {
    a: 1,
    b: 2
};

var obj2 = {...obj1};

console.log(obj1 === obj2); // false

obj2.c = 3; // Modifying obj2 will not affect obj1
console.log(obj1); // {a: 1, b: 2}
console.log(obj2); // {a: 1, b: 2, c: 3}

Note: The extension operator copy is a shallow copy and only works on the first level of the array or object.

5. Convert string to array

var str = 'hello';

// ES5 processing method var es5Arr = str.split('');
console.log(es5Arr) // ["h", "e", "l", "l", "o"]

// ES6 processing method var es6Arr = [...str];
console.log(es6Arr) // ["h", "e", "l", "l", "o"]

6. Use the extension operator when calling a function.

In the past, if we wanted to iterate array elements as function parameters, we generally used Function.prototype.apply.

function myFunction(x, y, z) { 
  console.log(x+""+y+""+z);
} 
var args = [0, 1, 2]; 
myFunction.apply(null, args);

With the spread syntax, we can write this.

function myFunction(x, y, z) { 
  console.log(x+""+y+""+z); 
} 

var args = [0, 1, 2]; 
myFunction(...args);

Tip: ...arr does not return an array, but the values ​​of each array. Only [...arr] is an array, so ...arr can be used to pass values ​​to methods.

Summarize

...The common methods and scenarios of the operator are as above. Other usage methods will not be introduced in detail, such as map and pseudo-array conversion. Interested friends can check the information by themselves. In fact, the essential usage is similar. To sum up: the three dots are placed on the formal parameter or the left side of the equal sign for the rest operator; placed on the actual parameter or the right side of the equal sign for the spread operator, or in other words, placed on the assigned side for the rest operator, and placed on the assigning side for the spread operator.

This concludes this article on the understanding and usage scenarios of the ES6 spread operator. For more relevant ES6 spread operator content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Summary of JavaScript spread operator usage examples [based on ES6]
  • Examples of using the ES6 spread operator
  • Detailed explanation of TS object spread operator and rest operator
  • Detailed explanation of the use and precautions of ES6 extension operator
  • ES6 extension operator and rest operator usage example analysis
  • ES6 array extension operator operation example analysis
  • JS ES new features: Introduction to extension operators

<<:  Jenkins+tomcat automatic hot deployment/restart and solutions to problems encountered (recommended)

>>:  MySQL 5.7.30 Installation and Upgrade Issues Detailed Tutorial

Recommend

MySQL 8.0.19 installation and configuration method graphic tutorial

This article records the installation and configu...

A brief discussion on whether CSS animation will be blocked by JS

The animation part of CSS will be blocked by JS, ...

JavaScript drag time drag case detailed explanation

Table of contents DragEvent Interface DataTransfe...

Detailed tutorial on installing VirtualBox and Ubuntu 16.04 under Windows system

1. Software Introduction VirtualBox VirtualBox is...

How to start tomcat using jsvc (run as a normal user)

Introduction to jsvc In production, Tomcat should...

Vue implements three-level navigation display and hiding

This article example shares the specific code of ...

Docker port mapping and external inaccessibility issues

The Docker container provides services and listen...

Detailed tutorial on installing the jenkins container in a docker environment

Recommended Docker learning materials: https://ww...

Four solutions for using setTimeout in JS for loop

Table of contents Overview Solution 1: Closures S...

Specific use of CSS front-end page rendering optimization attribute will-change

Preface When scroll events such as scroll and res...

MySQL column to row conversion and year-month grouping example

As shown below: SELECT count(DISTINCT(a.rect_id))...

A brief discussion on the problem of forgotten mysql password and login error

If you forget your MySQL login password, the solu...

MySQL initialization password operation under Mac

A simple record of the database startup problems ...