2020-08-04 15:13:35 +08:00
|
|
|
---
|
|
|
|
id: 587d7b88367417b2b2512b47
|
2020-12-16 00:37:30 -07:00
|
|
|
title: 将 rest 操作符与函数参数一起使用
|
2020-08-04 15:13:35 +08:00
|
|
|
challengeType: 1
|
|
|
|
forumTopicId: 301221
|
2021-01-13 03:31:00 +01:00
|
|
|
dashedName: use-the-rest-parameter-with-function-parameters
|
2020-08-04 15:13:35 +08:00
|
|
|
---
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --description--
|
|
|
|
|
|
|
|
ES6 推出了用于函数参数的<dfn>rest 操作符</dfn>帮助我们创建更加灵活的函数。在`rest`操作符的帮助下,你可以创建有一个变量来接受多个参数的函数。这些参数被储存在一个可以在函数内部读取的数组中。
|
|
|
|
|
2020-08-04 15:13:35 +08:00
|
|
|
请看以下代码:
|
|
|
|
|
|
|
|
```js
|
|
|
|
function howMany(...args) {
|
|
|
|
return "You have passed " + args.length + " arguments.";
|
|
|
|
}
|
|
|
|
console.log(howMany(0, 1, 2)); // You have passed 3 arguments.
|
|
|
|
console.log(howMany("string", null, [1, 2, 3], { })); // You have passed 4 arguments.
|
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
`rest`操作符可以避免查看`args`数组的需求,并且允许我们在参数数组上使用`map()`、`fiter()` 和 `reduce()`。
|
2020-08-04 15:13:35 +08:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --instructions--
|
2020-08-04 15:13:35 +08:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
修改`sum`函数,来让它使用`rest`操作符,并且它可以在有任何数量的参数时以相同的形式工作。
|
2020-08-04 15:13:35 +08:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --hints--
|
2020-08-04 15:13:35 +08:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
`sum(0,1,2)`的返回结果应该为3。
|
2020-08-04 15:13:35 +08:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(sum(0, 1, 2) === 3);
|
|
|
|
```
|
|
|
|
|
|
|
|
`sum(1,2,3,4)`的返回结果应该为10。
|
|
|
|
|
|
|
|
```js
|
|
|
|
assert(sum(1, 2, 3, 4) === 10);
|
2020-08-04 15:13:35 +08:00
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
`sum(5)`的返回结果应该为5。
|
2020-08-04 15:13:35 +08:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(sum(5) === 5);
|
|
|
|
```
|
2020-08-04 15:13:35 +08:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
`sum()`的返回结果应该为 0。
|
2020-08-04 15:13:35 +08:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
```js
|
|
|
|
assert(sum() === 0);
|
|
|
|
```
|
2020-08-04 15:13:35 +08:00
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
对`sum`函数的`args`参数使用了`...`展开操作符。
|
2020-08-04 15:13:35 +08:00
|
|
|
|
|
|
|
```js
|
2020-12-16 00:37:30 -07:00
|
|
|
assert(code.replace(/\s/g, '').match(/sum=\(\.\.\.args\)=>/));
|
2020-08-04 15:13:35 +08:00
|
|
|
```
|
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
# --seed--
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
```js
|
|
|
|
const sum = (x, y, z) => {
|
|
|
|
const args = [x, y, z];
|
|
|
|
return args.reduce((a, b) => a + b, 0);
|
|
|
|
}
|
|
|
|
```
|
|
|
|
|
2020-12-16 00:37:30 -07:00
|
|
|
# --solutions--
|
|
|
|
|
2021-01-13 03:31:00 +01:00
|
|
|
```js
|
|
|
|
const sum = (...args) => {
|
|
|
|
return args.reduce((a, b) => a + b, 0);
|
|
|
|
}
|
|
|
|
```
|