Home > Web Front-end > JS Tutorial > Quick Tip: How to Use the Spread Operator in JavaScript

Quick Tip: How to Use the Spread Operator in JavaScript

William Shakespeare
Release: 2025-02-09 09:58:13
Original
454 people have browsed it

Quick Tip: How to Use the Spread Operator in JavaScript

This tutorial will explain the various uses of extended operators in JavaScript, as well as the main differences between extended operators and residual operators.

JavaScript extension operator is represented by three dots (...) and is introduced in ES6. It can expand elements in collections and arrays into single elements.

Extended operators can be used to create and clone arrays and objects, pass arrays as function parameters, delete duplicates in arrays, and more.

Key Points

  • JavaScript extension operator is represented by three dots (...). It was introduced in ES6 to expand elements in sets and arrays into single elements. It can be used to create and clone arrays and objects, pass arrays as function parameters, delete duplicates in arrays, and more.
  • The extension operator can be used to clone arrays and objects, concatenate arrays, convert NodeList to arrays, and delete duplicates in arrays. However, it is important to note that it only performs shallow copies, which means it only copies the top-level elements or attributes. If an array or object contains other array or object, those arrays or objects are copied by reference, not by values.
  • The extension operator is different from the remaining operator, although both use the same syntax as three dots (...). The remaining operators can be used in the function's parameter list, indicating that the function accepts an undefined number of parameters, which can be processed as an array.

Grammar

Extended operators can only be used for iterable objects. It must be immediately before the iterable object, without any separation. For example:

console.log(...arr);
Copy after login
Copy after login

Function parameters

Take Math.min() method as an example. This method takes at least one number as a parameter and returns the smallest number of the passed parameters.

If you have an array of numbers and want to find the minimum value of these numbers, if there is no extension operator, you need to pass elements one by one with the index, or use the apply() method to pass elements of the array as arguments. For example:

const numbers = [15, 13, 100, 20];
const minNumber = Math.min.apply(null, numbers);
console.log(minNumber); // 13
Copy after login
Copy after login

Note that the first parameter is null, because the first parameter is used to change the value of this calling function.

The extension operator is a more convenient and readable solution for passing elements of an array as parameters to a function. For example:

const numbers = [15, 13, 100, 20];
const minNumber = Math.min(...numbers);
console.log(minNumber); // 13
Copy after login
Copy after login

You can see in this online example:

View the example on CodePen

Create an array

The

Extended operator can be used to create new arrays from existing arrays or other iterable objects containing the Symbol.iterator() method. These are objects that can be iterated with a for...of loop.

For example, it can be used to clone arrays. If you just assign the value of the existing array to a new array, making changes to the new array will update the existing array:

console.log(...arr);
Copy after login
Copy after login

By using the extension operator, you can clone an existing array into a new array, and any changes made to the new array will not affect the existing array:

const numbers = [15, 13, 100, 20];
const minNumber = Math.min.apply(null, numbers);
console.log(minNumber); // 13
Copy after login
Copy after login

It should be noted that this will only clone a one-dimensional array. It does not work with multidimensional arrays.

The extension operator can also be used to concatenate multiple arrays into one array. For example:

const numbers = [15, 13, 100, 20];
const minNumber = Math.min(...numbers);
console.log(minNumber); // 13
Copy after login
Copy after login

You can also use the extension operator for strings to create an array where each item is a character in the string:

const numbers = [15, 13, 100, 20];
const clonedNumbers = numbers;
clonedNumbers.push(24);
console.log(clonedNumbers); // [15, 13, 100, 20, 24]
console.log(numbers); // [15, 13, 100, 20, 24]
Copy after login

Create an object

Extension operators can be used to create objects in different ways.

It can be used to lightly clone another object. For example:

const numbers = [15, 13, 100, 20];
const clonedNumbers = [...numbers];
clonedNumbers.push(24);
console.log(clonedNumbers); // [15, 13, 100, 20, 24]
console.log(numbers); // [15, 13, 100, 20]
Copy after login

It can also be used to merge multiple objects into one object. For example:

const evenNumbers = [2, 4, 6, 8];
const oddNumbers = [1, 3, 5, 7];
const allNumbers = [...evenNumbers, ...oddNumbers];
console.log(...allNumbers); //[2, 4, 6, 8, 1, 3, 5, 7]
Copy after login

It should be noted that if the object shares the same property name, the property value of the last extended object will be used. For example:

const str = 'Hello, World!';
const strArr = [...str];
console.log(strArr); // ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
Copy after login

The extension operator can be used to create objects from an array where the index in the array becomes the attribute and the value at that index becomes the value of the attribute. For example:

const obj = { name: 'Mark', age: 20};
const clonedObj = { ...obj };
console.log(clonedObj); // {name: 'Mark', age: 20}
Copy after login

It can also be used to create objects from strings, similarly, the index in the string becomes the attribute, and the characters at that index become the value of the attribute. For example:

const obj1 = { name: 'Mark', age: 20};
const obj2 = { occupation: 'Student' };
const clonedObj = { ...obj1, ...obj2 };
console.log(clonedObj); // {name: 'Mark', age: 20, occupation: 'Student'}
Copy after login

Convert NodeList to an array

NodeList is a collection of nodes that are elements in the document. Unlike arrays, these elements are accessed through methods in a collection such as items or entries.

You can use the extension operator to convert NodeList to an array. For example:

const obj1 = { name: 'Mark', age: 20};
const obj2 = { age: 30 };
const clonedObj = { ...obj1, ...obj2 };
console.log(clonedObj); // {name: 'Mark', age: 30}
Copy after login

Delete duplicates in the array

Set object is a collection that stores only unique values. Similar to NodeList, Sets can be converted to arrays using the extension operator.

Since Set stores only unique values, it can be paired with the extension operator to delete duplicates in the array. For example:

const numbers = [15, 13, 100, 20];
const obj = { ...numbers };
console.log(obj); // {0: 15, 1: 13, 2: 100, 3: 20}
Copy after login

Extended operator and residual operator

The remaining operator is also a three-point operator (...), but it is used for different purposes. The remaining operators can be used in the function's parameter list, indicating that the function accepts an undefined number of parameters. These parameters can be processed as arrays.

Example:

const str = 'Hello, World!';
const obj = { ...str };
console.log(obj); // {0: 'H', 1: 'e', 2: 'l', 3: 'l', 4: 'o', 5: ',', 6: ' ', 7: 'W', 8: 'o', 9: 'r', 10: 'l', 11: 'd', 12: '!'}
Copy after login

In this example, the remaining operators are used as parameters to calculateSum function. You then iterate over the items in the array and add them to calculate their sum.

You can then pass the variables one by one to the calculateSum function as parameters, or use the extension operator to pass elements of the array as parameters:

const nodeList = document.querySelectorAll('div');
console.log(nodeList.item(0)); // <div>...</div>
const nodeArray = [...nodeList];
console.log(nodeArray[0]); // <div>...</div>
Copy after login

Conclusion

Extended operators allow you to do more with fewer lines of code while keeping the code readable. It can be used for iterable objects, passing parameters to functions, or creating arrays and objects from other iterable objects.

Related readings:

  • Missing mathematical method in JavaScript
  • Quick Tips: How to Sort Object Array in JavaScript
  • How to use for loop in JavaScript
  • Quick tip: Test whether the string matches the regular expression in JavaScript
  • 《JavaScript: From Newbie to Ninja》

JavaScript Extended Operator FAQs (FAQs)

(Frequently asked questions similar to the original FAQ content but with different wordings should be added here to maintain consistency of the content and avoid copying the original text directly)

The above is the detailed content of Quick Tip: How to Use the Spread Operator in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template