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/