其他分享
首页 > 其他分享> > 学习ECMAScript 2015【6】Default + Rest + Spread

学习ECMAScript 2015【6】Default + Rest + Spread

作者:互联网

0.前言

今天所要讨论的是:Default + Rest + Spread,看着有点糊涂,其实说全了,就是:default parameters, rest parameters and the spread operator.

image.png

1.总览

function f(x, y=12) {
  // y is 12 if not passed (or passed as undefined)
  return x + y;
}
f(3) == 15

function f(x, ...y) {
  // y is an Array
  return x * y.length;
}
f(3, "hello", true) == 6

function f(x, y, z) {
  return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6

2.展开谈谈

2.1.函数形参默认值

这没啥可说的,根据ES6: default, rest, and spread.中提到的那样,如果没有这东西,部分函数你得这么写:

function increment(number, increment){
  if (typeof increment == 'undefined' ) increment = 1;
  return number + increment;
} 

increment(1, 2) // 3
increment(1) // 2

有了默认值,就不用这么麻烦了,也不用在每个调用方那里看看有没有写默认值。

function increment(number, increment = 1){
  return number + increment;
} 

increment(5,5); // 10
increment(5); // 6

2.2.压缩多个元素到数组

function add(...numbers){
  return numbers.reduce((acc, number) => {
    return acc + number;
  }, 0);
}

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

add(2, 4, 6, 8, 10); // 30

没啥可说的,Java5就有变长参数了。就是方便你直接传变量,不用再单独封装一个数组。

2.3.将数组中的元素铺开

能拆就能建,就像构建有解构一样,数组这里组装和拆散也是对应可以使用的,比如把两个数组合并到一起。

// Array concatenation with spread
const array1 = ['Cersie', 'Jamie'];
const array2 = ['Tyrion'];

const lannisters = [...array1, ...array2];

console.log(lannisters); // ['Cersie' 'Jaime', 'Tyrion']

此法常见于Vue路由中静态路由、动态路由路径合并到一起添加到路由上。

结语

语法糖给我们方便,应该积极去学习和在恰当的时机使用。祝愿大家没有bug!

标签:function,...,return,Default,number,Rest,Spread,increment,路由
来源: https://blog.csdn.net/hengbao4/article/details/120952211