📜  解释扩展语法的好处以及它与 ES6 中的 rest 语法有何不同?

📅  最后修改于: 2022-05-13 01:56:54.935000             🧑  作者: Mango

解释扩展语法的好处以及它与 ES6 中的 rest 语法有何不同?

扩展运算符:扩展运算符或扩展语法允许我们在数组的情况下将数组和对象扩展为元素,在对象的情况下扩展键值对。扩展语法在 JavaScript 中由三个点 (...) 表示。

句法:

var my_var = [...array];

使用 Spread 语法的好处:

1. 它允许我们将数组或对象的所有元素包含在某种列表中。它可以扩展对象或数组并将所有值存储在相同数据类型的新变量中。

例子:

JavaScript


JavaScript


JavaScript


JavaScript


JavaScript


JavaScript


输出:

扩展数组和对象

2.它允许我们将已经存在的数组的所有元素复制到一个新的数组中,并执行push、pop操作,甚至不会干扰之前的数组。

例子:

JavaScript


输出:

3.它可以连接一个字符串或合并两个或多个数组,而无需使用concat()函数。

例子:

JavaScript


输出:

4. 它允许我们对数组进行数学运算。因为我们不能直接在数组上使用数学函数。扩展运算符将可迭代对象数组扩展为参数列表,允许我们操作数学函数并获得所需的结果。

例子:

JavaScript


输出:

Rest运算符:Rest 运算符的语法 类似于Spread运算符语法,其中spread运算符将数组扩展为其元素,另一方面rest 语法用于收集数据并将该数据存储到单个变量中,我们可以进一步将其传递给函数或可以在我们的代码作为变量。

句法:

function nameOfFunction(...data)
{
    // function statement
}

示例 1:下面的示例说明了 rest 语法的使用。

JavaScript


输出:

使用 rest 语法获取传递数据的总和

示例 2:

JavaScript


输出:

使用 rest 语法获取传递数据的乘积

Rest 和 Spread 语法之间的区别如下表所示:

                                 Spread Syntax                                                             Rest Syntax
Spread operator as its name suggests it spreads or expands the content of the given element. Rest Syntax is just the opposite of spread syntax it collects the data and stores that data in a variable which we can use further in our code.
It expands an Array in form of elements, while in key-value pairs in the case of Objects.It collects the data in the developer’s desired format. 
You may or may not use the strict mode inside the function containing the spread operator.You can not use the strict mode inside function containing the rest operator.
It will overwrite the identical properties inside two objects and replace the former with the latter.It simply collects all properties and wraps them inside a container.