{};"; 6. Convert the string to a character array, the syntax is "[...string]"."/> {};"; 6. Convert the string to a character array, the syntax is "[...string]".">

Home  >  Article  >  Web Front-end  >  How to use the spread operator in es6

How to use the spread operator in es6

青灯夜游
青灯夜游Original
2022-10-11 17:55:131869browse

es6 Usage of spread operator: 1. Copy array, syntax "[...array]"; 2. Merge arrays, syntax "[...array1,...array2]"; 3. Add elements to the array, the syntax is "[...array, 'element value']"; 4. Use it with the Math object to calculate the maximum value, minimum value or sum; 5. Pass infinite parameters to the function, the syntax is " const myFunc=(...args)=>{};"; 6. Convert the string to a character array, the syntax is "[...string]".

How to use the spread operator in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

Introduction to the spread operator in es6

The spread operator ... is introduced in ES6 and expands the iterable object to its individual elements , the so-called iterable object is any object that can be traversed using a for of loop, such as: array (common method of array), string, Map (understanding Map), Set (how to use Set?), DOM node, etc.

It is like the inverse operation of the rest parameter, converting an array into a sequence of parameters separated by commas. The spread operator can be used in conjunction with normal function parameters, and an expression can also be placed behind it, but if it is followed by an empty array, it will have no effect.

let arr = [];
arr.push(...[1,2,3,4,5]);
console.log(arr); //[1,2,3,4,5]
console.log(1, ...[2, 3, 4], 5) //1 2 3 4 5
console.log(...(1 > 0 ? ['a'] : [])); //a
console.log([...[], 1]); //[1]

Meaning

The apply method of the alternative function

Since the spread operator can expand the array, the apply method is no longer needed and the array is converted to function parameters.

10 ways to use the spread operator (...)

1. Copying an array

We can use the spread operator to copy an array, but be aware that this is a shallow copy.

const arr1 = [1,2,3];
const arr2 = [...arr1];
console.log(arr2);
// [ 1, 2, 3 ]

This way we can copy a basic array, note that it does not work with multi-level arrays or arrays with dates or functions.

2. Merge arrays

Suppose we have two arrays that we want to merge into one. In the early stage, we can use concat method, but now you can use the spread operator:

const arr1 = [1,2,3];
const arr2 = [4,5,6];
const arr3 = [...arr1, ...arr2];
console.log(arr3);
// [ 1, 2, 3, 4, 5, 6 ]

We can also use different arrangements to indicate which should come first.

const arr3 = [...arr2, ...arr1];
console.log(arr3);
[4, 5, 6, 1, 2, 3];

In addition, the expansion operator is also suitable for merging multiple arrays:

const output = [...arr1, ...arr2, ...arr3, ...arr4];

3. Add elements to the array

let arr1 = ['this', 'is', 'an'];
arr1 = [...arr1, 'array'];
console.log(arr1);
// [ 'this', 'is', 'an', 'array' ]

4. Add attributes to the object

Suppose you have an object of user, but it is missing an ageAttributes.

const user = {
  firstname: 'Chris',
  lastname: 'Bongers'
};

To add age to this user object, we can again utilize the spread operator.

const output = {...user, age: 31};

5. Use the Math() function

Suppose we have an array of numbers and we want to get the maximum value among these numbers. Minimum value or sum.

const arr1 = [1, -1, 0, 5, 3];

To get the minimum value, we can use the spread operator and the Math.min method.

const arr1 = [1, -1, 0, 5, 3];
const min = Math.min(...arr1);
console.log(min);
// -1

Similarly, to get the maximum value, you can do this:

const arr1 = [1, -1, 0, 5, 3];
const max = Math.max(...arr1);
console.log(max);
// 5

As you can see, the maximum value is 5, if we delete 5 , it will return 3.

You may be wondering, what happens if we don’t use the spread operator?

const arr1 = [1, -1, 0, 5, 3];
const max = Math.max(arr1);
console.log(max);
// NaN

This returns NaN because JavaScript doesn't know what the maximum value of the array is.

6. Rest parameter

Suppose we have a function with three parameters.

const myFunc(x1, x2, x3) => {
    console.log(x1);
    console.log(x2);
    console.log(x3);
}

We can call this function as follows:

myFunc(1, 2, 3);

But what happens if we want to pass an array.

const arr1 = [1, 2, 3];

We can use the spread operator to expand this array into our function.

myFunc(...arr1);
// 1
// 2
// 3

Here, we split the array into three separate parameters and pass them to the function.

const myFunc = (x1, x2, x3) => {
  console.log(x1);
  console.log(x2);
  console.log(x3);
};
const arr1 = [1, 2, 3];
myFunc(...arr1);
// 1
// 2
// 3

7. Pass unlimited parameters to the function

Suppose we have a function that accepts unlimited parameters as follows:

const myFunc = (...args) => {
  console.log(args);
};

If we now call this function with multiple parameters, we will see the following situation:

myFunc(1, 'a', new Date());

Return:

[
  1,
  'a',
  Date {
    __proto__: Date {}
  }
]

Then, we can dynamically loop through parameter.

8. Convert nodeList to an array

Suppose we use the spread operator to get all p## on the page #:

const el = [...document.querySelectorAll('p')];
console.log(el);
// (3) [p, p, p]
Here you can see that we got 3

p from the dom.

Now, we can easily iterate over these elements since they are arrays.

const el = [...document.querySelectorAll('p')];
el.forEach(item => {
  console.log(item);
});
// <p></p>
// <p></p>
// <p></p>

9. Destructuring variables

Deconstructing objects

Suppose we have an object

user:

const user = {
  firstname: 'Chris',
  lastname: 'Bongers',
  age: 31
};
Now we can use the spread operator to break this into individual variables.

const {firstname, ...rest} = user;
console.log(firstname);
console.log(rest);
// 'Chris'
// { lastname: 'Bongers', age: 31 }
Here, we deconstruct the

user object and firstname into the firstname variable and the rest of the object into restVariables.

解构数组

const [currentMonth, ...others] = [7, 8, 9, 10, 11, 12];
console.log(currentMonth); // 7
console.log(others); // [ 8, 9, 10, 11, 12 ]

10、展开字符串(字符串转字符数组)

String 也是一个可迭代对象,所以也可以使用扩展运算符 ... 将其转为字符数组,如下:

const title = "china";
const charts = [...title];
console.log(charts); // [ 'c', 'h', 'i', 'n', 'a' ]

进而可以简单进行字符串截取,如下:

const title = "china";
const short = [...title];
short.length = 2;
console.log(short.join("")); // ch

11、数组去重

与 Set 一起使用消除数组的重复项,如下:

const arrayNumbers = [1, 5, 9, 3, 5, 7, 10, 4, 5, 2, 5];
console.log(arrayNumbers);
const newNumbers = [...new Set(arrayNumbers)];
console.log(newNumbers); // [ 1,  5, 9, 3, 7, 10, 4, 2 ]

How to use the spread operator in es6

12、打印日志

在打印可迭代对象的时候,需要打印每一项可以使用扩展符,如下:

const years = [2018, 2019, 2020, 2021];
console.log(...years); // 2018 2019 2020 2021

【相关推荐:web前端开发

The above is the detailed content of How to use the spread operator in es6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:How to use es6 filter()Next article:How to use es6 filter()