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
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);
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
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
You can see in this online example:
Create an array
TheExtended 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);
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
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
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]
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]
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]
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', '!']
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}
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'}
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}
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}
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: '!'}
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>
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:
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!