函数参数——默认参数、剩余参数

274 阅读1分钟

函数参数——默认参数、剩余参数

默认参数

1.函数默认参数允许在没有值或undefined被传入时使用默认形参。

下面是例子:

function multiply(a, b = 1) {
  return a * b;
}

console.log(multiply(5, 2));
// expected output: 10

console.log(multiply(5));
// expected output: 5

函数参数默认值解决了一个问题。即es5时,需要自行在函数体赋予参数默认值之前需要给参数校验是否值为(a.)undefined或者(b.)未给参数赋值。

即在函数体里面第一行使用校验,并可能赋默认值。

b = ('undefined' === typeof b)?1:b;

2.遇到下面代码不可以省略参数而以为使用到了默认值

function multiply(a, b = 1,c) {
  return a * b * c;
}

console.log(multiply(5, 2));
// expected output: NaN

// 如果要使用默认值,一定要明确使用undefined
console.log(multiply(5,undefined,2));
// expected output: 10

如果遇到下面这个函数

function multiply(a, b = 1,c = 2) {
  return a * b * c;
}

console.log(multiply(5, 2));
// expected output: 20

console.log(multiply(5));
// expected output: 10

剩余参数

1.剩余参数使用,用在函数参数在一个位置

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

2第一个参数使用对象,结合解构赋值,在最后一个位置使用扩展运算符,将对象展开

同时使用rest参数比较下

function sum({a,b,...extendObj},...rest){
console.log(a);// expected output: 1
console.log(b);// expected output: 2
console.log(extendObj);// expected output: {c:3,d:4}
console.log([...rest]);// expected output: [123,123,123]
}
sum({a:1,b:2,c:3,d:4},123,123,123);

extendObj是es6(ES2017)的对象扩展运算符,在数组扩展运算符之后出现的。

代码例子,源于js参考 函数参数