2018-10-10 22:03:03 +00:00
|
|
|
---
|
|
|
|
id: 587d7b85367417b2b2512b3a
|
2021-03-04 17:49:46 +00:00
|
|
|
title: 调用函数时,捕获以错误顺序传递的参数
|
2018-10-10 22:03:03 +00:00
|
|
|
challengeType: 1
|
2020-09-07 08:09:54 +00:00
|
|
|
forumTopicId: 301184
|
2021-01-13 02:31:00 +00:00
|
|
|
dashedName: catch-arguments-passed-in-the-wrong-order-when-calling-a-function
|
2018-10-10 22:03:03 +00:00
|
|
|
---
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --description--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-04 17:49:46 +00:00
|
|
|
继续讨论调用函数,需要注意的下一个 bug 是函数的参数传递顺序错误。 如果参数分别是不同的类型,例如接受数组和整数两个参数的函数,参数顺序传错就可能会引发运行时错误。 对于接受相同类型参数的函数,传错参数也会导致逻辑错误或运行结果错误。 确保以正确的顺序提供所有必需的参数以避免这些问题。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --instructions--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-08 14:28:46 +00:00
|
|
|
函数 `raiseToPower` 返回基数 (base) 的指数 (exponent) 次幂。 不幸的是,它没有被正确调用 — 修改代码,使 `power` 的值为 8。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --hints--
|
2018-10-10 22:03:03 +00:00
|
|
|
|
2021-03-04 17:49:46 +00:00
|
|
|
你应修复变量 `power`,使其等于 2 的 3 次方,而不是 3 的 2 次方。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
assert(power == 8);
|
2018-10-10 22:03:03 +00:00
|
|
|
```
|
|
|
|
|
2021-03-04 17:49:46 +00:00
|
|
|
你调用 `raiseToPower` 函数时,传递参数的顺序应正确。
|
2018-10-10 22:03:03 +00:00
|
|
|
|
|
|
|
```js
|
2020-12-16 07:37:30 +00:00
|
|
|
assert(code.match(/raiseToPower\(\s*?base\s*?,\s*?exp\s*?\);/g));
|
2018-10-10 22:03:03 +00:00
|
|
|
```
|
2020-08-13 15:24:35 +00:00
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
# --seed--
|
|
|
|
|
|
|
|
## --seed-contents--
|
|
|
|
|
|
|
|
```js
|
|
|
|
function raiseToPower(b, e) {
|
|
|
|
return Math.pow(b, e);
|
|
|
|
}
|
|
|
|
|
|
|
|
let base = 2;
|
|
|
|
let exp = 3;
|
|
|
|
let power = raiseToPower(exp, base);
|
|
|
|
console.log(power);
|
|
|
|
```
|
|
|
|
|
2020-12-16 07:37:30 +00:00
|
|
|
# --solutions--
|
|
|
|
|
2021-01-13 02:31:00 +00:00
|
|
|
```js
|
|
|
|
function raiseToPower(b, e) {
|
|
|
|
return Math.pow(b, e);
|
|
|
|
}
|
|
|
|
|
|
|
|
let base = 2;
|
|
|
|
let exp = 3;
|
|
|
|
let power = raiseToPower(base, exp);
|
|
|
|
console.log(power);
|
|
|
|
```
|