【问题标题】:Spread Syntax vs Rest Parameter in ES2015 / ES6ES2015 / ES6 中的扩展语法与休息参数
【发布时间】:2016-02-27 04:20:19
【问题描述】:

我对 ES2015 中的扩展语法和 rest 参数感到困惑。谁能用恰当的例子解释它们之间的区别?

【问题讨论】:

  • 一个在调用点,一个在参数列表中。或者对于数组,一个在字面量中,另一个在解构表达式中。
  • 谁能解释为什么它被否决?
  • 可能是因为没有显示出研究成果。另外,您在哪里找到这些术语,它们在哪里/如何解释得如此糟糕以至于您无法区分?
  • @Bergi 个人意见,您的 cmets 提供的见解比公认的答案更多,只是说明 expandingcollapsing 并没有告诉他们的用例,谢谢 ;)
  • 我可能将此问题作为What do these three dots in React do? 的副本结束。为什么?因为这个问题明确地处理 both rest 参数语法和 spread 语法,而另一个问题 mainly 处理使用扩展语法。比结束这两个问题之一更重要的是,它们现在相互关联。这使他们都更容易找到。

标签: javascript ecmascript-6 variadic-functions spread-syntax rest-parameters


【解决方案1】:

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

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;

【讨论】:

  • const [a, b, ...c] = [1, 2, 3, 4, 5, 6, 7, 8, 9] 呢?
  • @yukulélé 这是rest。将其读取为 ab 和数组的其余部分。
  • @Yukulélé 剩下的,c 的值为 [3,4,5,6,7,8,9]
  • 你可以参考这个博客来了解rest / spread operator - tejassavaliya.medium.com/…
【解决方案2】:

ES6 新增三点...

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

  1. 作为休息/收集/收集
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. 随波逐流
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);

希望这会有所帮助。

【讨论】:

  • 目前看到的最容易理解最简单的解释。
  • 这是最好的答案。
  • 我喜欢你的回答。解释得很好。
  • @jtr13 这对我来说毫无意义。只需根据上下文给它一个具有不同功能的名称即可。
  • 这个解释很好。这是三个点... 的重要性以及我们如何使用 then 而不是 rest 和 spread 本身的单一定义。谢谢
【解决方案3】:

总结:

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

  1. 当在函数声明/表达式的函数参数中使用时,它会将剩余的参数转换为数组。这种变体被称为 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);

【讨论】:

【解决方案4】:

当我们在代码中看到“...”时,它要么是剩余参数,要么是 传播运算符。

有一种简单的方法可以区分它们:

当 ... 在函数参数的末尾时,它是“其余参数” 并将列表的其余部分收集到数组中。当 ... 出现在 函数调用或类似的,它被称为“扩展运算符”并扩展一个 数组到列表中。使用模式:

Rest 参数用于创建接受任意数量的函数 论据。扩展运算符用于将数组传递给函数 这通常需要许多参数的列表。他们一起帮助 轻松在列表和参数数组之间移动。 有关此click here的更多信息

【讨论】:

    【解决方案5】:

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

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

    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. 扩展运算符:允许将可迭代对象(数组/对象/字符串)扩展为单个参数/元素。

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

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

    【讨论】:

    • [T]rest 参数必须是最后一个收集其余元素的参数。 ~ * ~ 确认。好点子!干杯。
    【解决方案6】:

    基本上就像在 Python 中一样:

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

    【讨论】:

      【解决方案7】:

      在ES6中添加这三个点...有两个含义,Spread运算符和Rest参数

      扩展运算符:您使用三个点来扩展iterablesiterables 我的意思是arraysstring 等作为参数。例如,Math.max() 函数需要不确定数量的参数,因此您可以使用扩展运算符将元素扩展为 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定义

      其余参数语法允许我们表示一个不定数 参数作为数组。

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

      这里是来自 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
      

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

      希望有用。

      【讨论】:

        【解决方案8】:

        参考这个i cant understand how we are passing a function and returning arguments in javascript

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

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

        追踪:

        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]

        【讨论】:

          【解决方案9】:

          考虑 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' ]
          

          【讨论】:

            【解决方案10】:

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

            静止参数

            ES6 引入了rest 参数。 Rest 参数允许我们以数组的形式向函数发送任意数量的参数。 Rest参数只能是参数列表中的最后一个,并且只能有一个rest参数。在最后一个形参之前放置 rest operator(...) 表示该参数是一个 rest 参数。下面的例子展示了在最后一个形参之前添加一个 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 变量。剩余参数和参数变量之间的主要区别在于剩余参数是实数数组。所有数组方法都可用于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 
            

            【讨论】:

              【解决方案11】:

              简单易记............

              如果三点 (...) 在左侧,则为 Rest 参数,如果三点在右侧,则为 Spread 参数。

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

              【讨论】:

                猜你喜欢
                • 2018-08-01
                • 2020-02-24
                • 2023-04-04
                • 1970-01-01
                • 2015-12-18
                • 2017-12-24
                • 2016-10-09
                相关资源
                最近更新 更多