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

Blog    

Recommend

How to install and use Cockpit on CentOS 8/RHEL 8

Cockpit is a web-based server management tool ava...

Implementing simple tabs with js

Tab selection cards are used very frequently on r...

Summary of the dockerfile-maven-plugin usage guide

Table of contents pom configuration Setting.xml c...

Summary of shell's method for determining whether a variable is empty

How to determine whether a variable is empty in s...

A brief discussion on tags in HTML

0. What is a tag? XML/HTML CodeCopy content to cl...

How to modify the user and group of a file in Linux

In Linux, when a file is created, the owner of th...

How to set up cross-domain access in IIS web.config

Requirement: The page needs to display an image, ...

How to delete a MySQL table

It is very easy to delete a table in MySQL, but y...

MySQL select results to perform update example tutorial

1. Single table query -> update UPDATE table_n...

Syntax alias problem based on delete in mysql

Table of contents MySQL delete syntax alias probl...

react+antd.3x implements ip input box

This article shares the specific code of react+an...

Detailed analysis of the blocking problem of js and css

Table of contents DOMContentLoaded and load What ...

How to automatically delete records before a specified time in Mysql

About Event: MySQL 5.1 began to introduce the con...

Basic usage tutorial of IPTABLES firewall in LINUX

Preface For production VPS with public IP, only t...

MySQL intercepts the sql statement of the string function

1. left(name,4) intercepts the 4 characters on th...