在Rest参数中设置默认参数值是否可行?

19
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 =

任何帮助都非常感激。

3
在Edge浏览器上,我收到了错误信息:“The rest parameter cannot have a default initializer”。 - Nina Scholz
有趣。我几乎只使用Chrome,但那似乎是一个更有用的错误信息。感谢您的反馈。那似乎回答了其中的一些问题。 - IsenrichO
3个回答

18

不,剩余参数不能有默认初始化值。这是由于语法不允许初始值运行 - 参数总是被分配一个数组值(但可能是一个空数组)。

您想要做的事情可以通过以下方式实现:

function describePerson(name, ...traits) {
     if (traits.length == 0) traits[0] = 'a nondescript individual';
     return `Hi, ${name}! You are ${traits.join(', ')}`;
}
或者
function describePerson(name, firstTrait = 'a nondescript individual', ...traits) {
     traits.unshift(firstTrait);
     return `Hi, ${name}! You are ${traits.join(', ')}`;
}

// the same thing with spread syntax:
const describePerson = (name, firstTrait = 'a nondescript individual', ...otherTraits) =>
    `Hi, ${name}! You are ${[firstTrait, ...otherTraits].join(', ')}`

1
刚刚加入了一个更干净的默认系统:

const describePerson = (name, ...traits) => {
  traits = Object.assign(['x', 'y'], traits);

  return `Hi, ${name}, you are ${traits.join(', ')}`;
}

describePerson('z'); // you are z, y
describePerson('a', 'b', 'c'); // you are a, b, c
describePerson(); // you are x, y

这是因为数组是对象,其索引是键,Object.assign覆盖第二个对象中存在的第一个对象的键与第二个对象的值。如果第二个对象没有索引1,则不会被覆盖,但如果它有索引0,则第一个数组的索引0将被第二个数组覆盖,这是默认行为。
请注意,展开数组与展开对象不是相同的操作,因此[....['x', 'y'], ...traits]不会覆盖索引。

0

有一个解决方案:

const describePerson = (name, ...[
  first = 'a nondescript individual',
  ...traits
]) => `Hi, ${name}! You are ${[first, ...traits].join(', ')}`;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接