16

对函数调用使用可选链会导致表达式自动返回 undefined,而不是在找不到方法时抛出异常。

注意:代码使用的是spread syntax,而不是rest parameters

const fn1 = undefined
const args = []
const fn2 = () => {}
const fn3 = () => {}

console.log(fn1?.(...args, fn2, fn3))

错误:

console.log(fn1?.(...args, fn2, fn3))
                                ^
TypeError: Function.prototype.apply was called on undefined, which is an undefined and not a function
4

2 回答 2

8

It turns out to be a V8 bug, I've submitted it there, hopefully, it'll be fixed soon.

Update: it has been fixed.

于 2021-03-13T04:19:32.647 回答
-3

...rest 参数需要遵循一些规则。

其中一个规则是 ...rest 参数只能是最后一个参数。

foo(...one, ...wrong, ...wrong)
foo(...wrong, bad, bad)
foo(ok, ok, ...correct)

看:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

于 2021-03-13T03:04:36.533 回答