ES2015 / ES6 中的扩展语法与剩余参数

Spread Syntax vs Rest Parameter in ES2015 / ES6

我对 ES2015 中的扩展语法和剩余参数感到困惑。任何人都可以用适当的例子解释它们之间的区别吗?

使用传播时,您将单个变量扩展为更多:

var abc = ['a', 'b', 'c'];
var def = ['d', 'e', 'f'];
var alpha = [ ...abc, ...def ];
console.log(alpha)// alpha == ['a', 'b', 'c', 'd', 'e', 'f'];

当使用剩余参数时,您会将一个函数的所有剩余参数折叠到一个数组中:

function sum( first, ...others ) {
    for ( var i = 0; i < others.length; i++ )
        first += others[i];
    return first;
}
console.log(sum(1,2,3,4))// sum(1, 2, 3, 4) == 10;

ES6 有新特性三点...

以下是我们如何使用这些点:

  1. As Rest/Collector/Gather
var [c, ...m] = [1,2,3,4,5]; // m -> [2,3,4,5]

这里...m是一个收集器,它收集剩下的参数。在我们写的内部:

var [c, ...m] = [1,2,3,4,5]; JavaScript 关注

var c = 1,
    m = [2, 3, 4, 5];
  1. As Spread
var params = [ "hello", true, 7 ];
var other = [ 1, 2, ...params ]; // other => [1,2,"hello", true, 7]

此处,...params 传播以便将其所有元素添加到 other

在内部JavaScript执行以下操作

var other = [1, 2].concat(params);

希望对您有所帮助。

基本上和Python一样:

>>> def func(first, *others):
...    return [first, *others]
>>> func('a', 'b', 'c')
['a', 'b', 'c']

When we see "..." in the code, it is either rest parameters or the spread operator.

There’s an easy way to distinguish between them:

When ... is at the end of function parameters, it’s “rest parameters” and gathers the rest of the list into the array. When ... occurs in a function call or alike, it’s called a “spread operator” and expands an array into the list. Use patterns:

Rest parameters are used to create functions that accept any number of arguments. The spread operator is used to pass an array to functions that normally require a list of many arguments. Together they help to travel between a list and an array of parameters with ease. For more information about this click here

ES6中新增的这三个点...有两个意思,Spread运算符和Rest参数

展开运算符:你用三个点展开iterables,通过iterables我的意思是arraysstring等作为参数。例如 Math.max() 函数需要不确定数量的参数,因此您可以使用 Spread 运算符将元素扩展为 Math.max() 函数的参数。这是来自 mdn

的示例
console.log(Math.max(1, 3, 2));
// expected output: 3

console.log(Math.max(-1, -3, -2));
// expected output: -1

var array1 = [1, 3, 2];

console.log(Math.max(...array1));
// expected output: 3

另一个用例是添加,例如有这个数组

const videoGames = ['mario galaxy', 'zelda wind waker', 'ico'];

您可以将它添加到另一个数组

const favoritesVideoGames = ['Shadow of the colosus', ...videoGames];

favoritesVideoGames值为

[ 'Shadow of the colosus', 'mario galaxy', 'zelda wind waker', 'ico' ]

关于Rest参数,这里MDN定义

The rest parameter syntax allows us to represent an indefinite number of arguments as an array.

这意味着您可以将许多元素打包到一个元素中

这里是来自 MDN 的例子

function sum(...theArgs) {
  return theArgs.reduce((previous, current) => {
    return previous + current;
  });
}

console.log(sum(1, 2, 3));
// expected output: 6

console.log(sum(1, 2, 3, 4));
// expected output: 10

我经常对这三点感到困惑,这个illustration by @stephaniecodes帮助我记住它的逻辑。我提到我从这个插图中得到灵感来回答这个问题。

希望有用。

总结:

在 javascript 中 ... 被重载。它根据运算符的使用位置执行不同的操作:

  1. 当在函数的函数参数中使用时 declaration/expression 它将把剩余的参数转换成一个数组。此变体称为 Rest parameters 语法。
  2. 在其他情况下,它将在需要零个或多个参数(函数调用)或元素(数组文字)的地方展开可迭代的值。这种变体称为 Spread 语法。

示例:

剩余参数语法:

function rest(first, second, ...remainder) {
  console.log(remainder);
}

// 3, 4 ,5 are the remaining parameters and will be 
// merged together in to an array called remainder 
rest(1, 2, 3, 4, 5);

传播语法:

// example from MDN:

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

// the numbers array will be spread over the 
// x y z parameters in the sum function
console.log(sum(...numbers));


// the numbers array is spread out in the array literal
// before the elements 4 and 5 are added
const newNumbers = [...numbers, 4, 5];

console.log(newNumbers);

Javascript 的 三点 ( ... ) 运算符 可以两种不同的方式使用:

  1. rest参数:将所有剩余的元素收集到一个数组中。

var days = ["Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri"];
const [sat, sun, ...weekdays] = days;
console.log(sat); // "Sat"
console.log(sun); // "Sun"
console.log(weekdays); // ["Mon", "Tue", "Wed", "Thu", "Fri"]

  1. 扩展运算符: 允许将可迭代对象(数组/对象/字符串)扩展为单个arguments/elements.

var weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri"];
var days = [...weekdays, "Sat", "Sun"]; 
console.log(days) // ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

注意展开运算符可以是第一个元素,但是rest参数需要是最后一个来收集其余元素。

参照此i cant understand how we are passing a function and returning arguments in javascript

函数是一组指令,它接受一些输入并处理它们并 returns 结果。

这里我们有一个数组 [1, 2, 3, 4, 5, 6],过滤器函数遍历每个元素并将每个元素传递给正函数,如果它是偶数,则 returns , 否则跳过它。

跟踪:

1 => Filter(1) => positive(1) => skips 1,
2 => Filter(2) => positive(2) => returns 2,
3 => Filter(3) => positive(3) => skips 3,
...
6 => Filter(6) => positive(6) => returns 6

因此结果 [2, 4, 6]

考虑 3 种情况

1] 不使用任何运算符

function add(x, y) {
  return x + y;
}

add(1, 2, 3, 4, 5) // returns 3  (function will takes first 2 arg only)

2] 与休息运算符

function add(...args) {
  let result = 0;

  for (let arg of args) result += arg;

  return result
}

add(1) // returns 1
add(1,2) // returns 3
add(1, 2, 3, 4, 5) // returns 15

- 我们可以将任意数量的参数收集到一个数组中

3] 带扩展运算符

const arr = ["Joy", "Wangari", "Warugu"];
const newArr = ["joykare", ...arr];

The value of newArr will be [ 'joykare', 'Joy', 'Wangari', 'Warugu' ]

另一个

function add(a, b, c) {
  return a + b + c ;
}
const args = [1, 2, 3];

add(...args);

-We have been using arrays to demonstrate the spread operator, 
but any iterable also works. So, if we had a 
string const str = 'joykare', [...str] translates to [ 'j', 'o', 'y', 'k', 'a', 'r', 'e' ]

来自:Ved Antani,Stoyan Stefanov 的书“面向对象 JavaScript - 第三版。” :

其余参数

ES6引入了rest参数。 Rest 参数允许我们以数组的形式向函数发送任意数量的参数。 rest参数只能是参数列表中的最后一个,rest参数只能有一个。在最后一个形式参数之前放置一个 rest operator(...) 表示该参数是一个 rest 参数。以下示例显示在最后一个形式参数之前添加一个剩余运算符:

function sayThings(tone, ...quotes){ 
  console.log(Array.isArray(quotes)); //true 
  console.log(`In ${tone} voice, I say ${quotes}`) 
} 
sayThings("Morgan Freeman","Something serious"," 
 Imploding Universe"," Amen"); 
//In Morgan Freeman voice, I say Something serious,
 Imploding Universe,Amen 

传递给函数的第一个参数以音调接收,其余参数以数组形式接收。可变参数 (var-args) 已经成为其他几种语言的一部分,并且是 ES6 的受欢迎版本。 Rest 参数可以替代略有争议的 arguments 变量。剩余参数和 arguments 变量之间的主要区别在于剩余参数是真正的数组。 rest 参数可以使用所有数组方法。

展开运算符

spread 运算符看起来与 rest 运算符完全一样,但执行完全相反的功能。 Spread 运算符用于在调用函数或定义数组时提供参数。 spread 运算符 获取数组 将其元素 拆分为单个变量。以下示例说明了 spread 运算符如何在调用以数组作为参数的函数时提供更清晰的语法:

function sumAll(a,b,c){ 
  return a+b+c 
} 
var numbers = [6,7,8] 
//ES5 way of passing array as an argument of a function 
console.log(sumAll.apply(null,numbers)); //21 
//ES6 Spread operator 
console.log(sumAll(...numbers))//21 

简单易记......

如果三点 (...) 位于其 Rest 参数的左侧,则三点中的点位于其 Spread 参数的右侧。

const [a,b,...c] = [1,2,3,4,5]     // (left) rest

const [d,e] = [1, ...c]             // (right) spread