Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between the JavaScript expansion operator and the remainder operator

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what is the difference between JavaScript expansion operator and residual operator". In daily operation, I believe many people have doubts about the difference between JavaScript expansion operator and residual operator. Xiaobian consulted all kinds of data and sorted out a simple and useful method of operation. I hope it will be helpful to answer the question of "what is the difference between JavaScript expansion operator and residual operator". Next, please follow the editor to study!

JavaScript uses the sign three dots (...) as the remainder operator and the expansion operator, but there is a difference between the two operators.

The main difference is that the residual operator places the rest of some specific values provided by the user into the JavaScript array, while the unfold operator expands the iterable object into a single element.

For example, the following code uses the remaining operator to store some values in an array:

/ / Use rest to enclose the rest of specific user-supplied values into an array:function myBio (firstName, lastName,... otherInfo) {return otherInfo;} / / Invoke myBio function while passing five arguments to its parameters:myBio ("Oluwatobi", "Sofela", "CodeSweetly", "Web Developer", "Male"); / / The invocation above will return: ["CodeSweetly", "Web Developer", "Male"]

View the running results

In the above code, we use. OtherInfo to store the rest of the "CodeSweetly", "We Developer" and "Male" arguments of the incoming function myBio () into an array.

Then let's look at the following example, where the expansion operator is used:

/ / Define a function with three parameters:function myBio (firstName, lastName, company) {return `${firstName} ${lastName} runs ${company}`;} / / Use spread to expand an array's items into individual arguments:myBio (. ["Oluwatobi", "Sofela", "CodeSweetly"]); / / The invocation above will return: "Oluwatobi Sofela runs CodeSweetly"

View the running results

In the above code, we use the expansion operator (...) to expand the contents of the array ["Oluwatobi", "Sofela", "CodeSweetly" one by one and pass them to the arguments of the function myBio ().

If you are not familiar with the remainder operator and the expansion operator, don't worry too much, we will introduce them later in this article.

In the following sections, we will discuss in detail how the remaining and unfold operators work in JavaScript.

What is the remainder operator?

As mentioned above, the remainder operator puts the rest of some specific values provided by the user into the JavaScript array. The syntax is as follows:

... yourValues

The three dots (...) in the above code are used to represent the remaining operators.

The content after the remaining operator is used to indicate the values you want to populate the array. Note that the remaining operator can only be used in the last parameter defined by the function.

How does the remainder operator work in the JavaScript function?

In the JavaScript function, the remainder operator is used before the last argument of the function. Such as the following code:

/ / Define a function with two regular parameters and one rest parameter:function myBio (firstName, lastName,... otherInfo) {return otherInfo;}

Here, the remaining operator tells the JavaScript program to add any value provided by the user to the parameter otherInfo to an array. The array is then assigned to the otherInfo parameter.

Therefore, we call it the remaining parameter. OtherInfo.

It is important to note that the remaining arguments passed to the function when called are optional.

Another example:

/ / Define a function with two regular parameters and one rest parameter:function myBio (firstName, lastName,... otherInfo) {return otherInfo;} / / Invoke myBio function while passing five arguments to its parameters:myBio ("Oluwatobi", "Sofela", "CodeSweetly", "Web Developer", "Male"); / / The invocation above will return: ["CodeSweetly", "Web Developer", "Male"]

View the running results

In the above code, the function myBio () is called with five arguments, while the function myBio () has only three arguments. That is, the parameters "Oluwatobi" and "Sofela" are passed to firstName and lastName, respectively, and the other parameters ("CodeSweetly", "Web Developer" and "Male") are passed to the remaining parameter otherInfo. So, the result returned by the function myBio () is ["CodeSweetly", "Web Developer", "Male"], all of which are the contents of the remaining parameter otherInfo.

Be careful! "use strict" cannot be used in the body of a function that contains remaining parameters

Remember, you cannot use the "use strict" directive in any function body that contains remaining parameters, default parameters, or parameter deconstruction. Otherwise, JavaScript will report a syntax error.

Consider the following code:

/ / Define a function with one rest parameter:function printMyName (... value) {"use strict"; return value;} / / The definition above will return: "Uncaught SyntaxError: Illegal 'use strict' directive in function with non-simple parameter list"

Note: "use strict" can be placed outside the function only if the entire script or closed scope is in strict mode.

Now that we know what the residual operator does in a function, let's take a look at how it works in parameter deconstruction.

How does the residual operator work in parameter deconstruction?

The residual operator is usually used before the last variable when a parameter is deconstructed and assigned. Here is an example:

/ Define a destructuring array with two regular variables and one rest variable:const [firstName, lastName,... otherInfo] = ["Oluwatobi", "Sofela", "CodeSweetly", "Web Developer", "Male"]; / / Invoke the otherInfo variable:console.log (otherInfo); / / The invocation above will return: ["CodeSweetly", "Web Developer", "Male"]

View the running results

The remaining operator (...) here tells the JavaScript program to add all the other values provided by the user to an array. The array is then assigned to the otherInfo variable.

Therefore, we call the... otherInfo here a residual variable.

Another example:

/ Define a destructuring object with two regular variables and one rest variable:const {firstName, lastName,... otherInfo} = {firstName: "Oluwatobi", lastName: "Sofela", companyName: "CodeSweetly", profession: "Web Developer", gender: "Male"} / / Invoke the otherInfo variable:console.log (otherInfo); / / The invocation above will return: {companyName: "CodeSweetly", profession: "Web Developer", gender: "Male"}

View the running results

Notice in the above code that the remainder operator assigns a property object (instead of an array) to the otherInfo variable. That is, when you use the residual operator when deconstructing an object, it generates a property object instead of an array.

However, if you use the residual operator when deconstructing an array or function, it will generate the array literal.

You should have noticed that there are some differences between JavaScript arguments and the remaining parameters, so let's take a look at these differences.

What is the difference between JavaScript arguments and the remaining parameters?

Here are some of the differences between JavaScript arguments and the remaining parameters:

The difference is that the 1:arguments object is an array-like object, but it's not a real array!

Keep in mind that JavaScript arguments objects are not real arrays. It is an object similar to an array and does not have any of the properties that an array has.

The remaining parameter is a real array on which you can use any method that the array has. For example, you can use the sort (), map (), forEach (), or pop () methods for one of the remaining parameters. But you cannot use these methods on arguments objects.

Difference 2: you cannot use the arguments object in the arrow function

The arguments object is not available in the arrow function, and the remaining parameters are available in all functions, including the arrow function.

Difference 3: give priority to the remaining parameters

The remaining parameters are preferred over arguments objects, especially when writing ES6-compatible code.

Now that we have seen how the residue operator works, let's discuss the expansion operator and see the difference between it and the residue operator.

What is the unfold operator and how does it work in JavaScript?

The expansion operator (...) expands an iterable object into a single element.

The expansion operator can be applied to array literals, function calls, and initialized property objects, which expand the values of iterable objects into separate elements one by one. In fact, it is the opposite of the remaining operator.

Note that the expansion operator is only valid when using array literals, function calls, or initialized property objects.

Let's look at some practical examples.

Example 1: how the unfold operator works in an array literal

Const myName = ["Sofela", "is", "my"]; const aboutMe = ["Oluwatobi",... myName, "name."]; console.log (aboutMe); / / The invocation above will return: ["Oluwatobi", "Sofela", "is", "my", "name."]

View the running results

In the above code, the expansion operator (...) copies the array myName into aboutMe.

Note:

Any changes to myName are not reflected in aboutMe. Because all values in the myName array are primitives. The extension operator simply copies and pastes the contents of the myName array into aboutMe without creating any references to the original array elements.

The unfold operator only makes a shallow copy. So, when the myName array contains any non-native values, JavaScript creates a reference between myName and aboutMe. For more information on how the unfold operator handles both native and non-native values, you can see here.

Suppose we don't use the expansion operator to copy the contents of the array myName, for example, we write this line of code const aboutMe = ["Oluwatobi", myName, "name."] in this case JavaScript will assign a reference to myName so that all changes made to the myName array are reflected in the aboutMe array.

Example 2: how to use the unfold operator to convert a string to an array

Const myName = "Oluwatobi Sofela"; console.log ([... myName]); / / The invocation above will return: ["O", "l", "u", "w", "a", "t", "o", "b", "I", "S", "o", "f", "e", "l", "a"]

View the running results

In the above code, we use the expansion operator ([...]) in the array literal to expand the value of the myName string into an array. Thus, the contents of the string "Oluwatobi Sofela" are expanded into the array ["O", "l", "u", "w", "a", "t", "o", "b", "I", "", "S", "o", "f", "e", "l", "a"].

Example 3: how the unfold operator works in a function call

Const numbers = [1, 3, 5, 7]; function addNumbers (a, b, c, d) {return a + b + c + d;} console.log (addNumbers (..)); / / The invocation above will return:16

View the running results

In the above code, we use the expansion operator to expand the contents of the array numbers and pass it to the parameters of the function addNumbers (). If the array numbers has more than four elements, JavaScript only passes the first four elements as arguments to the function addNumbers () and ignores the rest.

Here are some other examples:

Const numbers = [1, 3, 5, 7, 10, 200, 90, 59]; function addNumbers (a, b, c, d) {return a + b + c + d;} console.log (addNumbers (...)); / / The invocation above will return:16

View the running results

Const myName = "Oluwatobi Sofela"; function spellName (a, b, c) {return a + b + c;} console.log (spellName (.. myName)); / / returns: "Olu" console.log (spellName (. MyName [3]); / / returns: "wundefinedundefined" console.log (spellName ([... MyName])) / / returns: "returns returns:" spellName ({... myName}); / / returns: "[object Object] undefinedundefined"

View the running results

Example 4: how the unfold operator works in the literals of an object

Const myNames = ["Oluwatobi", "Sofela"]; const bio = {... myNames, runs: "codesweetly.com"}; console.log (bio); / / The invocation above will return: {0: "Oluwatobi", 1: "Sofela", runs: "codesweetly.com"}

View the running results

In the above code, we use the expansion operator inside the bio object to expand the value of the array myNames into individual properties.

What we need to know about the expansion operator

Keep the following three basic information in mind when using the expansion operator.

1. The expansion operator cannot expand the value of the literal amount of an object.

Because the property object is non-iterable, its value cannot be expanded using the unfold operator. However, you can use the expansion operator to clone the properties of one object to another.

Look at the following example:

Const myName = {firstName: "Oluwatobi", lastName: "Sofela"}; const bio = {... myName, website: "codesweetly.com"}; console.log (bio); / / The invocation above will return: {firstName: "Oluwatobi", lastName: "Sofela", website: "codesweetly.com"}

View the running results

In the above code, we use the expansion operator to clone the contents of the myName object into the bio object.

Note:

The unfold operator can only expand the values of iterable objects.

An object is iterable only if it contains an attribute with @ @ iterator key.

Array,TypedArray,String,Map,Set are built-in iterable types because they all have the @ @ iterator attribute by default.

The property object is a non-iterable array type because it does not have the @ @ iterator property by default.

You can add @ @ iterator to a property object to make it iterable.

two。 The unfold operator does not clone the same attribute

Suppose we use the expansion operator to clone the properties of object A to object B. if object B contains the same attributes as object A, then the properties of object B will override the properties of object A. In other words, in this process, those properties in object A that are the same as object B are not cloned.

Look at the following example:

Const myName = {firstName: "Tobi", lastName: "Sofela"}; const bio = {... myName, firstName: "Oluwatobi", website: "codesweetly.com"}; console.log (bio); / / The invocation above will return: {firstName: "Oluwatobi", lastName: "Sofela", website: "codesweetly.com"}

View the running results

Notice that the expansion operator does not copy the value of the firstName property of the myName object to the bio object, because the object bio already contains the firstName property.

3. Notice how the unfold operator works in objects that contain non-primitives

If you use the unfold operator on an object (or array) that contains only the original value, JavaScript does not create any references between the original object and the copied object.

Look at the following code:

Const myName = ["Sofela", "is", "my"]; const aboutMe = ["Oluwatobi",... myName, "name."]; console.log (aboutMe); / / The invocation above will return: ["Oluwatobi", "Sofela", "is", "my", "name."]

View the running results

Note that each element in myName is a primitive value, so when we clone myName to aboutMe using the expansion operator, JavaScript does not create any references between the two arrays. Therefore, any changes made to the myName array are not reflected in the aboutMe array, and vice versa.

Let's add an element to the myName array:

MyName.push ("real")

Now let's check the values of myName and aboutMe:

Console.log (myName); / ["Sofela", "is", "my", "real"] console.log (aboutMe); / / ["Oluwatobi", "Sofela", "is", "my", "name."]

Note that our changes to the myName array are not reflected in the aboutMe array because the expansion operator does not create any references between the original array and the copied array.

What if the myName array contains non-primitive items?

Assume that myName contains non-primitive items, in which case the expansion operator creates a reference between the non-primitive and cloned items of the primitive array.

Look at the following example:

Const myName = [["Sofela", "is", "my"]; const aboutMe = ["Oluwatobi",... myName, "name."]; console.log (aboutMe); / / The invocation above will return: ["Oluwatobi", ["Sofela", "is", "my"], "name."]

View the running results

Notice that the myName array here contains a non-primitive entry.

Therefore, when the contents of myName are cloned to aboutMe using the expansion operator, JavaScript creates a reference between the two arrays. In this way, any changes to the myName array are reflected in the aboutMe array, and vice versa.

As an example, we also add an element to the myName array:

MyName [0] .push ("real")

Now let's look at the values of myName and aboutMe:

Console.log (myName); / / [["Sofela", "is", "my", "real"] console.log (aboutMe); / / ["Oluwatobi", ["Sofela", "is", "my", "real"], "name."]

View the running results

Note that the changes to the myName array are reflected in the aboutMe array because the expansion operator creates a reference between the original array and the copied array.

Another example:

Const myName = {firstName: "Oluwatobi", lastName: "Sofela"}; const bio = {... myName}; myName.firstName = "Tobi"; console.log (myName); / / {firstName: "Tobi", lastName: "Sofela"} console.log (bio); / / {firstName: "Oluwatobi", lastName: "Sofela"}

View the running results

In the above code, the update to myName is not reflected in the bio object because we use the unfold operator on objects that contain only the original values.

Note that developers often refer to the myName here as a shallow object because it contains only the original items.

Another example:

Const myName = {fullName: {firstName: "Oluwatobi", lastName: "Sofela"}}; const bio = {... myName}; myName.fullName.firstName = "Tobi"; console.log (myName); / / {fullName: {firstName: "Tobi", lastName: "Sofela"} console.log (bio); / / {fullName: {firstName: "Tobi", lastName: "Sofela"}}

View the running results

In the above code, the update of myName is reflected in the bio object because we use the expansion operator on objects that contain non-literal values.

Note:

We call the myName here a deep object because it contains non-primitive items.

When you clone one object to another, if a reference is created, a shallow copy is made. For example,... myName produces a shallow copy of the myName object, because any changes you make to one object are reflected in the other object.

When cloning one object to another, a deep copy is made if no reference is created. For example, I can deeply copy the myName object into the bio object with const bio = JSON.parse (JSON.stringify (myName)). In this way, JavaScript will clone the myName into bio without creating any references.

We can cut off the reference between myName and bio by replacing the fullname sub-object in myName or bio with a new object. For example, use myName.fullName = {firstName: "Tobi", lastName: "Sofela"} to break the pointer between myName and bio.

At this point, the study of "what is the difference between the JavaScript expansion operator and the rest operator" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report