29

JavaScript剩余操作符Rest Operator

 4 years ago
source link: https://www.tuicool.com/articles/nmi2qaB
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

本文适合JavaScript初学者阅读

剩余操作符

之前这篇文章 JavaScript展开操作符(Spread operator)介绍 讲解过展开操作符。剩余操作符和展开操作符的表示方式一样,都是三个点 '...',但是他们的使用场景会不同。

剩余参数

定义函数的时候,如果函数的参数以… 为前缀,则改参数是剩余参数(rest parameter)。剩余参数表示参数个数不确定的参数列表。在函数被调用时,该形参会成为一个数组,数组中的元素都是传递给该函数的多出来的实参的值。

获取参数

剩余操作符可以用来方便地获取传进来的参数。

function sum(a,b,...args){
  console.log(args.length); // 传进来的参数的个数 3
  let s = a + b;
  if(args && args.length){
      args.forEach(i => {s += i});
  }  
 return s;
}
sum(1, 2, 3, 4, 5 ); // 传进来的参数的个数 3

其中第一个形参a对应的是1,第二个形参b对应的2,…args表示的就是[3, 4, 5]。

和arguments的差别

上面剩余参数args是一个数组,而函数的arguments是一个伪数组。应此剩余参数可以使用数组的相关方法sort,map,forEach,pop,而arguments不能。

arguments想要变成数组,可以通过Array.prototype.slice.call方法,使用剩余操作符可以避免将arguments转为数组的麻烦。

// 下面的代码模拟了剩余数组
function sum(a,b,){
  var args = Array.prototype.slice.call(arguments, sum.length);  
  console.log(args.length); // 传进来的参数的个数 3
  let s = a + b;
  args.forEach(i => {s += i});
 return s;
}
sum(1, 2, 3, 4, 5 );

而使用剩余操作符,则不需要转化,直接使用,更加方便。

剩余操作符与解构赋值

我们知道,ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。 比如如下代码:

let array = [1,2,3]
let [a,b,c] = array; // a 1, b 2, c 3

再比如如下代码:

let obj = {a:1,b:2,c:3}
let {a,b,c} = obj; // a 1, b 2, c 3

在解构赋值时,可以使用剩余操作符。剩余操作符所操作的变量会匹配在解构赋值中所有其他变量未匹配到的属性。

比如如下代码,others会匹配到first和second对于属性的余下的属性:

const { first, second, ...others } = {
  first: 1,
  second: 2,
  third: 3,
  fourth: 4,
  fifth: 5
}

first // 1
second // 2
others // { third: 3, fourth: 4, fifth: 5 }

对象中余下的属性值被打包起来构造一个新的对象赋值给了 others

数组也可以通过剩余操作符,把剩余的元素打包成一个新的数组赋值给剩余属性,代码如下:

let array = [1,2,3,4,5];
let [a,b,...c] = array;  // a 1,b 2, c [3,4,5]

剩余操作符和展开操作符

某种程度上,可以任务剩余操作符是展开操作符的相反操作。展开操作符会”展开“数组编程多个元素,剩余操作符会把多个元素压缩成一个单一的元素。

欢迎关注公众号“ITman彪叔”。彪叔,拥有10多年开发经验,现任公司系统架构师、技术总监、技术培训师、职业规划师。熟悉Java、JavaScript。在计算机图形学、WebGL、前端可视化方面有深入研究。对程序员思维能力训练和培训、程序员职业规划和程序员理财投资有浓厚兴趣。

NVFJjyY.jpg!web


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK