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

JavaScript implements Tab bar switching effects

Here is a case that front-end developers must kno...

MySQL data operation-use of DML statements

illustrate DML (Data Manipulation Language) refer...

A Brief Analysis of MySQL Connections and Collections

Join query A join query refers to a matching quer...

Mysql join query principle knowledge points

Mysql join query 1. Basic concepts Connect each r...

Introduction to major browsers and their kernels

Trident core: IE, MaxThon, TT, The World, 360, So...

Practical explanation of editing files, saving and exiting in linux

How to save and exit after editing a file in Linu...

How to set background color and transparency in Vue

Background color and transparency settings As sho...

How to unify the character set on an existing mysql database

Preface In the database, some data tables and dat...

Vue3 compilation process-source code analysis

Preface: Vue3 has been released for a long time. ...

Installation and use of Apache stress testing tools

1. Download Go to the Apache official website htt...

How to deploy MySQL master and slave in Docker

Download image Selecting a MySQL Image docker sea...

Detailed explanation of how to install MySQL on Alibaba Cloud

As a lightweight open source database, MySQL is w...

Complete steps to implement face recognition login in Ubuntu

1. Install Howdy: howdy project address sudo add-...

MySQL lock control concurrency method

Table of contents Preface 1. Optimistic Locking A...