Home>Article>Web Front-end> An article explaining in detail the different ways to use the spread operator in JavaScript
This article will take you through the different ways of using spread operators in JavaScript, as well as the main differences between spread operators and remainder operators. I hope it will be helpful to you!
is represented by three dots (...
). The JavaScript spread operator was introduced in ES6. It can be used to expand elements in collections and arrays into single individual elements.
The spread operator can be used to create and clone arrays and objects, pass arrays as function arguments, remove duplicates from arrays, and more.
The spread operator can only be used on iterable objects. It must be used before the iterable object without any separation. For example:
console.log(...arr);
Take the Math.min() method as an example. This method accepts at least one number as argument and returns the smallest number among the passed arguments.
If you have an array of numbers and you want to find the minimum among these numbers, then without the spread operator you need to pass the elements one by one using their index, or use apply() Method to pass array as parameter. For example:
const numbers = [15, 13, 100, 20]; const minNumber = Math.min.apply(null, numbers); console.log(minNumber); // 13
Please note that the first parameter isnull
because the first parameter is used to change the value ofthis
calling function.
The spread operator is a more convenient and readable solution for passing array elements as arguments to functions. For example:
const numbers = [15, 13, 100, 20]; const minNumber = Math.min(...numbers); console.log(numbers); // 13
The spread operator can be used to create a new array from an existing array or other iterable object that contains the Symbol.iterator() method. These are objects that can be iterated over using afor...of
loop.
For example, it can be used to clone an array. If you simply assign the values of an existing array to a new array, making changes to the new array will update the existing array:
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]
An existing array can be cloned into a new array by using the spread operator , and any changes made to the new array will not affect the existing array:
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]
It should be noted that this will only clone a one-dimensional array. It does not work with multidimensional arrays.
The spread operator can also be used to concatenate multiple arrays into one. 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]
You can also use the spread operator on a string to create an array where each item is a character in the string:
const str = 'Hello, World!'; const strArr = [...str]; console.log(strArr); // ['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
The spread operator can be used in different ways to create objects.
It can be used to shallow clone another object. For example:
const obj = { name: 'Mark', age: 20}; const clonedObj = { ...obj }; console.log(clonedObj); // {name: 'Mark', age: 20}
It can also be used to merge multiple objects into one. 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'}
It should be noted that if objects share the same property name, the value expanded by the last object will be used. For example:
const obj1 = { name: 'Mark', age: 20}; const obj2 = { age: 30 }; const clonedObj = { ...obj1, ...obj2 }; console.log(clonedObj); // {name: 'Mark', age: 30}
The spread operator can be used to create an object from an array, where the index in the array becomes the property and the value at that index becomes the value of the property. For example:
const numbers = [15, 13, 100, 20]; const obj = { ...numbers }; console.log(obj); // {0: 15, 1: 13, 2: 100, 3: 20}
It can also be used to create an object from a string, where the index in the string becomes a property and the character at that index becomes the value of the property. For 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: '!'}
NodeListis a collection of nodes, which are elements in the document. Elements are accessed through methods in the collection, such asitem
orentries
, unlike arrays.
You can use the spread operator to convert a NodeList to an Array. For example:
const nodeList = document.querySelectorAll('div'); console.log(nodeList.item(0)); //...const nodeArray = [...nodeList]; console.log(nodeList[0]); //...
A Set object is a collection that stores only unique values. Similar to NodeList, a Set can be converted to an array using the spread operator.
Since a Set only stores unique values, it can be paired with the spread operator to remove duplicates from an array. For example:
const duplicatesArr = [1, 2, 3, 2, 1, 3]; const uniqueArr = [...new Set(duplicatesArr)]; console.log(duplicatesArr); // [1, 2, 3, 2, 1, 3] console.log(uniqueArr); // [1, 2, 3]
rest operator is also a three-dot operator (...
), but It is used for different purposes. The rest operator can be used in the argument list of a function to indicate that the function accepts an undefined number of arguments. These parameters can be handled as arrays.
For example:
function calculateSum(...funcArgs) { let sum = 0; for (const arg of funcArgs) { sum += arg; } return sum; }
In this example, the rest operator is used as an argument to thecalculateSum
function. You then loop through the items in the array and add them to calculate their sum.
You can then pass the variables one by onecalculateSum
as arguments to the function, or use the spread operator to pass elements of the array as arguments:
console.log(calculateSum(1, 2, 3)); // 6 const numbers = [1, 2, 3]; console.log(calculateSum(...numbers)); // 6
The spread operator allows you to do more with fewer lines of code while keeping the code readable. It can be used with iterables to pass arguments to functions, or to create arrays and objects from other iterables.
【Related recommendations:javascript video tutorial,Basic programming video】
The above is the detailed content of An article explaining in detail the different ways to use the spread operator in JavaScript. For more information, please follow other related articles on the PHP Chinese website!