ES6引入了许多方便的“语法糖”。其中包括JavaScript函数的默认参数功能和rest参数。我发现当尝试在rest参数上设置默认参数值时,我的控制台(或devTools)会抱怨(即抛出错误)。我在其他地方找到了惊人地少关于这个特定问题的参考资料,并且想知道1.)是否可能这样做以及2.)为什么不行(假设不可能)。
任何帮助都非常感激。
作为示例,我构造了一个微不足道的(但希望仍然有用的)示例。在这个函数的第一次迭代中,我构建了函数,使其可以正常工作(也就是说,没有给rest参数设置默认值)。
const describePerson = (name, ...traits) => `Hi, ${name}! You are ${traits.join(', ')}`;
describePerson('John Doe', 'the prototypical placeholder person');
// => "Hi, John Doe! You are the prototypical placeholder person"
然而,现在默认情况下:
const describePerson = (name, ...traits = ['a nondescript individual']) => `Hi, ${name}! You are ${traits.join(', ')}`;
describePerson('John Doe');
// => Uncaught SyntaxError: Unexpected token =
任何帮助都非常感激。