by Joanna Gaudyn
乔安娜·高登(Joanna Gaudyn)
JavaScript(ES6)传播算子和rest参数简介 (An intro to the spread operator and rest parameter in JavaScript (ES6))
扩展运算符和rest参数都被写为三个连续的点(…)。 他们还有其他共同点吗? (Both the spread operator and the rest parameter are written as three consecutive dots (…). Do they have anything else in common?)
点差运算符(…) (The spread operator (…))
The spread operator was introduced in ES6. It provides you with the ability to expand iterable objects into multiple elements. What does it really mean? Let’s check some examples.
点差运算符 在ES6中引入。 它使您能够将可迭代对象扩展为多个元素。 到底是什么意思 让我们来看一些例子。
const movies = ["Leon", "Love Actually", "Lord of the Rings"];console.log(...movies);
Prints:
印刷品:
Leon Love Actually Lord of the Rings
莱昂·洛夫实际上是指环王
const numbers = new Set([1, 4, 5, 7]);console.log(...numbers);
Prints:
印刷品:
1 4 5 7
1 4 5 7
You might notice that both the array from the first example and the set from the second one have been expanded into their individual elements (strings and digits respectively). How can this be of any use, you may ask.
您可能会注意到,第一个示例中的数组和第二个示例中的数组都已扩展为它们各自的元素(分别为字符串和数字)。 您可能会问,这怎么用?
The most common use is probably combining arrays. If you ever had to do this in the times before the spread operator, you probably used the concat()
method.
最常见的用途可能是组合数组。 如果您曾经在传播运算符之前的某个时间执行此操作,则可能使用了concat()
方法。
const shapes = ["triangle", "square", "circle"];const objects = ["pencil", "notebook", "eraser"];const chaos = shapes.concat(objects);console.log(chaos);
Prints:
印刷品:
[“triangle”, “square”, “circle”, “pencil”, “notebook”, “eraser”]
[“三角形”,“正方形”,“圆形”,“铅笔”,“笔记本”,“橡皮擦”]
That’s not too bad, but what the spread operator offers is a shortcut, which makes your code look way more readable too:
这还不错,但是散布运算符提供的是一种快捷方式,这也使您的代码看起来也更具可读性:
const chaos = [...shapes, ...objects];console.log(chaos);
Prints:
印刷品:
[“triangle”, “square”, “circle”, “pencil”, “notebook”, “eraser”]
[“三角形”,“正方形”,“圆形”,“铅笔”,“笔记本”,“橡皮擦”]
Here’s what we’d get if we tried doing the same without the spread operator:
如果我们尝试在没有传播运算符的情况下执行相同操作,则会得到以下结果:
const chaos = [shapes, objects];console.log(chaos);
Prints:
印刷品:
[Array(3), Array(3)]
[Array(3),Array(3)]
What happened here? Instead of combining the arrays, we got a chaos
array with the shapes
array at index 0 and the objects
array at index 1.
这里发生了什么? 我们没有合并数组,而是获得了一个chaos
数组,其中shapes
数组位于索引0, objects
数组位于索引1。
其余参数(…) (The rest parameter (…))
You can think of the rest parameter as the opposite of the spread operator. Just as the spread operator allows you to expand an array into its individual elements, the rest parameter lets you bundle elements back into an array.
您可以将rest参数视为与散布运算符相反的参数。 正如散布运算符允许您将数组扩展为单个元素一样,rest参数可以让您将元素捆绑回到数组中。
将数组的值分配给变量 (Assigning values of an array to variables)
Let’s have a look at the following example:
让我们看下面的例子:
const movie = ["Life of Brian", 8.1, 1979, "Graham Chapman", "John Cleese", "Michael Palin"];const [title, rating, year, ...actors] = movie;console.log(title, rating, year, actors);
Prints:
印刷品:
“Life of Brian”, 8.1, 1979, [“Graham Chapman”, “John Cleese”, “Michael Palin”]
“布莱恩生活”,8.1,1979年,[“格雷厄姆·查普曼”,“约翰·克莱斯”,“迈克尔·帕林”]
The rest parameter let us take the values of the movie
array and assign them to several individual variables using destructuring. This way title
, rating
, and year
are assigned the first three values in the array, but where the real magic happens is actors
. Thanks to the rest parameter, actors
gets assigned the remaining values of the movie
array, in form of an array.
rest参数让我们采用movie
数组的值,并使用destructuring将它们分配给几个单独的变量。 这样,将title
, rating
和year
分配给数组中的前三个值,但是真正发生魔术的地方是actors
。 多亏了rest参数, actors
以数组的形式被分配了movie
数组的剩余值。
可变函数 (Variadic functions)
Variadic functions are functions which take an indefinite number of arguments. One good example is the sum()
function: we can’t know upfront how many arguments will be passed to it:
可变参数函数是带有不确定数量的参数的函数。 一个很好的例子是sum()
函数:我们无法预先知道将有多少参数传递给它:
sum(1, 2);sum(494, 373, 29, 2, 50067);sum(-17, 8, 325900);
In earlier versions of JavaScript, this kind of function would be handled using the arguments object, which is an array-like object, available as a local variable inside every function. It contains all values of arguments passed to a function. Let’s see how the sum()
function could be implemented:
在JavaScript的早期版本中,此类函数将使用arguments对象处理, arguments对象是一个类似于数组的对象,可以在每个函数内部作为局部变量使用。 它包含传递给函数的参数的所有值。 让我们看看如何实现sum()
函数:
function sum() { let total = 0; for(const argument of arguments) { total += argument; } return total;}
It does work, but it’s far from perfect:
它确实有效,但远非完美:
If you look at the definition for the
sum()
function, it doesn’t have any parameters. It can be quite misleading.如果查看
sum()
函数的定义,则其中没有任何参数。 这可能会产生误导。It can be hard to understand if you’re not familiar with the arguments object (as in: where the heck are the
arguments
coming from?!)如果您不熟悉arguments对象,可能很难理解(例如:
arguments
从何而来?!)
Here’s how we’d write the same function with the rest parameter:
这是我们使用rest参数编写相同函数的方式:
function sum(...nums) { let total = 0; for(const num of nums) { total += num; } return total;}
Note that the for...in
loop has been replaced with the for...of
loop as well. We made our code more readable and concise at once.
请注意, for...in
循环也已被for...of
循环替换。 我们使代码一次更可读,更简洁。
Hallelujah ES6!
哈利路亚ES6!
Are you just starting your journey with programming? Here’s some articles that might interest you as well:
您刚刚开始编程之旅吗? 以下是一些您可能也会感兴趣的文章:
Is a coding bootcamp something for you?
编码训练营适合您吗?
Is career change really possible?
职业转变真的有可能吗?
Why Ruby is a great language to start programming with
为什么Ruby是一门很好的编程语言
翻译自: https://www.freecodecamp.org/news/spread-operator-and-rest-parameter-in-javascript-es6-4416a9f47e5e/